Search code examples
cpointersstructstackundeclared-identifier

"Undeclared" value for value declared inside struct


I'm trying to implement/understand stacks and I keep getting "value undeclared" for something that is declared inside the struct that is supposed to represent the stack

#define EmptyTOS ( -1 )
#define MinStackSize ( 5 )

typedef struct StackRecord *Stack;

struct StackRecord
{
    int Capacity;
    int TopOfStack;
    int *Array;
};

Stack CreateStack( int MaxElements )
{
    Stack S;    
    S = malloc( sizeof( struct StackRecord ) );
    S->Array = malloc( sizeof( int ) * MaxElements );
    S->Capacity = MaxElements;
    MakeEmpty( S );
    return S;
}

void MakeEmpty( Stack S ){
    S->TopOfStack = EmptyTOS;
}

void Push( int X, Stack S ){
    S->Array[++TopOfStack] = X;
}

int main(){

    Stack s1 = CreateStack(10);

    return 0;
}

If I try to compile just this I get: In function ‘Push’: error: ‘TopOfStack’ undeclared I don't understand why


Solution

  • It is because TopOfStack is not declared.

    If you want to access the member variable of the object pointed at by S, you should write S->TopOfStack.