简体   繁体   中英

Difference between malloc(sizeof(ptr)) and malloc(sizeof(ptr*))?

I want to know what is the difference between these two lines:

 queue* f=(queue*)malloc(sizeof(queue));
 queue* f=(queue*)malloc(sizeof(queue*));

Here's the definition of queue:

typedef struct queue
{
    int arr[N];
    int tail;
}queue;

Thanks in advance!

The difference is that the second line is wrong; it allocates enough space to store a pointer to a queue , not a queue itself, but it's assigned to a type that assumes it points to enough space for a whole queue .

Neither one requires a cast , so the correct form is:

queue *f = malloc(sizeof(queue));

To be even safer, don't refer to the type itself, refer to the variable you're assigning to, to avoid repeating the type (potentially causing maintenance problems if the type is changed); this also means sizeof doesn't need parentheses :

queue *f = malloc(sizeof *f);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM