0

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 Answer 1

1
  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. I.e.

     for (int i = 0; i < length; ++i) { free(bar[i]); } 
     free(bar);
    
Sign up to request clarification or add additional context in comments.

1 Comment

Interesting, I was told by somebody that the size of a Foo* should be Foo,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.