hello friends...
1.

struct node *p;
p=malloc(sizeof(struct node));

2.

struct node *p;
    p=malloc(sizeof(struct node *));

what is the difference between 1 and 2 code :)
pls help

Recommended Answers

All 2 Replies

What it comes down to is that sizeof(struct node) gives the size of a struct node element, while sizeof(struct node *) gives the size of a pointer to a struct node element. So, if struct node is

struct node 
{
    int data;
    struct node* next;
}

Then, on a typical 32-bit machine, sizeof(struct node*) would probably be four (4 bytes == 32 bits), while sizeof(struct node) would be equal to sizeof(int) + sizeof(struct node*) (possibly with some additional padding as well, to align the data on a word boundary, though probably not in this instance), which would likely (but not definitely) come to eight bytes. Note that you can't assume the sizes are what you'd expect them to be, because different types of system have different pointer and data sizes; this is why you use the sizeof operator, even for the primitive types.

The difference between code 1 and 2 is that the code 2 is erroneous.

malloc() allocates memory of the given size and returns a pointer to that memory. If you allocate memory big enough to store one struct node then you would store the pointer in a struct node* pointer, as in code 1. So, in code 2, because the destination pointer is struct node*, the malloc function should be given sizeof(struct node). Or, if you use sizeof(struct node*), then the result should be stored in a struct node** pointer (i.e., pointer to a pointer to a node).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.