I’m teaching myself C since my uni seems to be obsessed with java, so im writing a stack implementation of type int (ill worry about making it generic later). I came across an error that makes not sense to me, missing ';' before 'type'. As far as i can tell my syntax is right, if it is not please do tell. Anyways here is my code:
stack.h
typedef struct{
int *elements;
int size;
int capacity;
}Stack;
void newStack(Stack *s);
void delStack(Stack *s);
void pushToStack(Stack *s, int value);
int popFromStack(Stack *s);
stack.c
#include "stack.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
void newStack(Stack *s){
s->size = 0;
s->capacity = 4;
s->elements = (int*) malloc(4 * sizeof(int));
assert(s->elements != NULL); // allocation worked?
}
void delStack(Stack *s){
free(s->elements);
}
void pushToStack(Stack *s, int value){
if(s->size == s->capacity){
s->size *= 2;
s->elements = (int *) realloc(s->elements, s->size * sizeof(int));
assert(s->elements !=NULL); //reallocation worked?
}
s->elements[s->size] = value;
s->size++;
}
int popFromStack(Stack *s){
assert(s->size>0);
s->size --;
return s->elements[s->size];
}
int main()
{
Stack s1;
newStack(&s1);
int i;
for(i=0; i<3; i++){
pushToStack(&s1, i);
printf("%d ", i);
}
printf("\n");
for(i=0; i<3; i++){
printf("%d ", popFromStack(&s1));
}
delStack(&s1);
getchar();
return 0;
}
The error occurs in main, on the int i; line, but if i move the line up the error goes away and the program runs flawlessly. I want to know why.
CAUSES ERROR:
newStack(&s1);
int i;
NO ERROR:
int i;
newStack(&s1);
PS: just in case it matters.. im using MS Visual Studio 2010
Visual Studio is stuck in a time loop somewhere before 1998, back when the standard mandated that all declarations should be at the beginning of a block.
This was changed in C99, and MS does say it supports the most popular features. Sadly this is not one of them.