Click here to Skip to main content
15,914,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Considering my struct:

typedef struct node *Node; 
struct node{     
  Item value;     
  struct node *next; 
};


What is the difference between these three statements?

1. Node n = malloc(sizeof(struct node));
2. Node n = malloc(sizeof(Node));
3. struct node *n = malloc(sizeof(struct node));


What I have tried:

I noticed that the second one create problems with the input. Is there actually a difference between these?
Posted
Updated 9-Jul-21 6:26am

1 solution

Statements 1. and 3. are equivalent, and allocate a block of memory the size of struct node

Statement 2, on the other hand, allocates a block of memory the size of Node. Now, Node has been typedef-ed to struct node *, so statement 2 could be rewritten as
C
Node n = malloc(sizeof(struct node *))
This allocates a block for a pointer, not the size of the thing the pointer points to. For most systems in use today, that will either be 4 or 8 bytes, depending on whether the the system uses 32 or 64 bits natively.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900