Anant Anant - 2 months ago 10
C Question

Declaration and initialisation of pointers in C

I'm brushing up on the initialization and declaration of pointers in C.

I wrote a piece of code :

struct node
{
int data;
struct node* right=NULL;
struct node* left=NULL;
};

struct node* newNode(int data)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));

temp->data = data;

return temp;
}


which returned an error. The error is :


expected ';' at end of declaration list

struct node* right=NULL;



I then changed the code to :

struct node
{
int data;
struct node* right;
struct node* left;
right = NULL;
left = NULL;

};

struct node* newNode(int data)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));

temp->data = data;

return temp;
}


which returned the same error.

Finally,

I changed the code to :

struct node
{
int data;
struct node* right;
struct node* left;
};

struct node* newNode(int data)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));

temp->data = data;
temp->right=NULL;
temp->left=NULL;

return temp;
}


The above piece of code compiles without any errors. Why is this so ?

Answer

You cannot initialize a struct member inside a struct declaration. You have to do it outside, in your code. The struct declaration declares a type, not a variable that can be initialized.

Comments