Question

[Solved] malloc an array of struct pointers vs array of structs

What’s the difference between

struct mystruct *ptr = (struct test *)malloc(n*sizeof(struct test));

and

struct mystruct **ptr = (struct test *)malloc(n*sizeof(struct test *));

They both work fine, I’m just curious about the actual difference between the two. Does the first one allocate an array of structs, whereas the second one an array of struct pointers? The other way around? Also, which one has a smaller memory footprint?

Enquirer: alf

||

Solution #1:

The first allocates an array of struct, and the other allocates an array of pointers to struct. In the first case, you can write to fields by assigning ptr[0].field1 = value; right away, while in the second case you must allocate the struct itself before doing the actual writing.

It is OK to drop the cast of malloc result in C, so you could write

struct mystruct **ptr = malloc(n*sizeof(struct test *));
for (int i = 0; i != n ; i++) {
    ptr[i] = malloc(sizeof(struct test));
}
ptr[0]->field1 = value;
...
// Do not forget to free the memory when you are done:
for (int i = 0; i != n ; i++) {
    free(ptr[i]);
}
free(ptr);

Solution #2:

I’m just curious about the actual difference between the two

The function malloc doesn’t deal in structures or pointers. It only understands bytes. So the first allocates enough bytes for n struct test objects, which the second allocates enough space for n struct test * objects.

They both work fine

The way things look, the 2 would be used for wildly different things. For example, in the second case, you’d have to allocate memory for each ptr[i] element.

Also, which one has a smaller memory footprint

You can answer that yourself if you print sizeof(struct test) and sizeof(struct test *). But again, they’re different things, with different purposes. Which has a smaller footprint, a tractor or a beetle ?

Respondent: cnicutar

Solution #3:

The first allocates an array of structs. The second allocates an array of pointers to structs (no memory for the structs themselves). So the second is smaller unless of course your struct is also very small like a pointer.

Respondent: TJD

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy