-2

I am a new C learner and have a question. Can I assign memory to different struct pointer at same time? Like this:

head,next,n1=malloc(sizeof(node));

Head next and n1 are pointers of type struct and node is struct name. Will this create 3 different struct pointers in memory?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
kalyani
  • 13
  • 1

3 Answers3

3

No you cannot, what you can do is make all the pointers points to the same adress:

head=next=n1=malloc(sizeof(node));

Same as:

n1 = malloc(sizeof(node));
next = n1;
head = next;
Dr.Haimovitz
  • 1,568
  • 12
  • 16
0

This expression statement that is valid in C

head,next,n1=malloc(sizeof(node));

consists of three subexpressions that are operands of the comma operator.

You can imagine it like

( head ), ( next ), ( n1=malloc(sizeof(node)) );

So as you can see only n1 is assigned with the value returned by the call of malloc.

You could write instead

head = next = n1 = malloc(sizeof(node));

but again in this case function malloc is called once and its value is assigned to three pointers n1, next and head. That is all three pointers will have the same value - the address of the allocated memory by this one call of malloc.

So if you want that each pointer would point to its own allocated memory then you have to call malloc three times.

head = malloc(sizeof(node));
next = malloc(sizeof(node));
n1 = malloc(sizeof(node));
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

in C the ","(comma) operator is used to define multiple variables of the same type. For example:

int n1, next, head;

But can not be used to assign a value to a variable. To do that you need to use the assigning operator "="(equal). For example:

head = next = n1 = malloc(sizeof(node));
p4p1
  • 31
  • 5