I am trying to create a struct object (stack) which consists of:
typedef struct node {
int val;
struct node * next;
}node_t;
typedef struct {
node_t * top;
int max_size;
int used_size;
} Stack;
However, when I try to initialize the object and allocate it some memory space using the function:
Stack * newStack(int max_size) {
Stack * S = malloc(sizeof(Stack));
S->top = NULL;
S->max_size = max_size;
S->used_size = 0;
return S;
}
Stack * S = newStack(256); //error here
I get the error referred to above -
function call is not allowed in constant expression
I have never come across this type of error before, and I don't know how to tackle it. Any help is appreciated.
In C language objects with static storage duration can only be initialized with constant expressions.
You are initializing a global variable S
, which is an object with static storage duration. Your expression newStack(256)
is not a constant expression. As the compiler told you already, you are not allowed to call functions in constant expressions. Hence the error. That's all there is to it.
If you want to have a global variable S
, then the only way to "initialize" it with newStack(256)
is to do it inside some function at program startup. E.g.
Stack * S;
int main()
{
S = newStack(256);
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With