0

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?

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

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.