简体   繁体   中英

initializing a 2-D array of structs pointers in C

I'm using -std=gnu99 when I compile. Suppose I had a struct like this:

typedef struct Foo {
    char *quux;
    int baz;
} Foo;

I noticed that you can initialize a 1D array of structs with NULL values in the heap like this:

Foo* bar[10] = {[0 ... 9] = NULL};

But how would I do this for a 2D array on the heap? Here is my attempt:

int depth = 10;
int length = 10;
Foo **bar;

bar = malloc(sizeof(Foo) * length);

for (int i = 0; i < length; i++) {

    bar[i] = (Foo*) calloc(depth, sizeof(Foo));

}

And when I go to release this memory, would I free() 10 times, or 100 times? And what about the variable length of foo.quux?

  1. First, there is an error in the following line:

     bar = malloc(sizeof(Foo) * length);

Should be

    bar = malloc(sizeof(Foo*) * length);

As you want to allocate enough space for a Foo* which will signify the start of your array. The original line will allocate space for a Foo.

  1. If you allocated the 2D array in the style above, you would do 11 free() in total, one for each sub array you allocated (10), and one for the array of pointers you allocated. Ie

     for (int i = 0; i < length; ++i) { free(bar[i]); } free(bar);

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