tomato
tomato

Reputation: 841

Allocating memory for a 2d array of pointers wrapped within an struct in C

Let's say I have a struct named 'Foo' and inside of that I have a 2d array of pointers

      typedef struct Foo {
          Stuff* (*stuff)[16];
      } Foo;

I have an initializeFoo function like so that allocates memory for the whole object

      void initializeFoo(Foo **foo) {
          *foo = (Foo*)malloc(sizeof(Foo));
      }

However, with just that I result in a Segmentation fault(core dumped) when running my program I was thinking that I need to allocate the memory for *stuff, but how would I do that? And would I stick that in the initializeFoo function?

My guess would be to use:

    (*foo)->stuff = (Stuff*(*)[16])malloc(sizeof(Stuff))

Can someone help me out?

Upvotes: 0

Views: 1041

Answers (2)

Brian Kocoloski
Brian Kocoloski

Reputation: 61

To tell for certain, I would need to see all of your code, but my guess is that the double pointer that you pass to initializeFoo itself has not been allocated.

For example, if you do:

Foo ** foo;
initializeFoo(foo);

Your program will segfault because you dereference foo, which has not been allocated. However, if you use:

Foo * foo;
initializeFoo(&foo);

or

Foo ** foo = (Foo **)malloc(sizeof(Foo *));
initializeFoo(foo);

and your program still segfaults, then the problem must lie elsewhere.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409146

Yes you need to allocate memory for stuff. Also, what you have now is actually a three-dimensional "array".

You also doesn't allocate enough memory for stuff.

It might actually be simpler to just use pointer-to-pointer to simulate a two-dimensional array:

typedef struct Foo {
    Stuff **stuff;
} Foo;

Then in initializeFoo:

void initializeFoo(Foo **foo)
{
    *foo = malloc(sizeof(Foo));

    /* Allocate first dimension, 32 items */
    (*foo)->stuff = malloc(sizeof(Stuff *) * 32);

    /* Allocate second dimension, 16 items each */
    for (int i = 0; i < 32; i++)
        (*foo)->stuff[i] = malloc(sizeof(Stuff) * 16);
}

Upvotes: 2

Related Questions