-6

So we have a struct that is actually representing a node of a linked list. Also a pointer that points to node.

typedef struct node{
    int value;
    struct node *next;
}node;

node* head=NULL;

If I am going to dynamically allocate the pointer using malloc,

head=malloc(sizeof(node));

that means that I am creating some memory space, with size of node, and head is pointing at it.

I would like to know the difference between this head=malloc(sizeof(node*));, as you can see in the sizeof it has node* instead of node. Now I really think that all this time I had no idea what malloc really does!

Mr T
  • 506
  • 2
  • 9
  • 26
  • 1
    `malloc` will give you a pointer to some memory at least as big as the size that you ask for (although sometimes it will return `NULL`, on failure). Did you try actually printing out `sizeof(node)` versus `sizeof(node *)` to see what you get? – Ricky Mutschlechner Feb 17 '16 at 18:19
  • You do not "allocate a pointer", but an object of the type it **points to** and assign the address to the pointer. Now think which size you have to pass to `malloc`. – too honest for this site Feb 17 '16 at 18:20

3 Answers3

3
head=malloc(sizeof(node*));

Will allocate a space in memory to hold a POINTER to a object of type node.

head=malloc(sizeof(node));

Will allocate space for the structure itself, and return to you the address of that memory space, and you will hold that in the head variable

For more info, check this other question about Malloc. How do free and malloc work in C?

Community
  • 1
  • 1
Ulysses
  • 2,281
  • 1
  • 16
  • 24
2

sizeof(node) is the size in bytes of the whole struct, which can be arbitrarily large. sizeof(node*) is the size of a pointer variable, which is fixed, no matter how large is the structure (and it is pretty small on most systems).

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
1
head=malloc(sizeof(node*));

is incorrect. That call to malloc allocates enough memory to hold only a node*. A node* must point to a node object. That means you need to allocate sufficient memory to hold a node object, not a node*.

R Sahu
  • 204,454
  • 14
  • 159
  • 270