Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign NULL to structure member

Tags:

c

Here is the code

struct stack {
    int item;
    struct stack *next=NULL;
};

I want to make the pointer initially point to null but this shows error

error:expected ':' , ',' , ';' , '}' or 'attribute' before'=' token

like image 685
salih Avatar asked Dec 13 '25 05:12

salih


1 Answers

The fragment posted does not define an object, it defines a type.

In C you cannot specify the default value of a member in a type definition. You can specify the values of members in an initializer:

struct stack {
    int item;
    struct stack *next;
};

struct stack my_stack = { 0, NULL };

If you omit the last member in the initializer, it will be initialized to the zero of its type, NULL for a pointer:

struct stack my_stack = { 0 };  // my_stack.next is NULL
like image 72
chqrlie Avatar answered Dec 14 '25 18:12

chqrlie