简体   繁体   English

为包装在C中的结构中的二维指针数组分配内存

[英]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 假设我有一个名为“ Foo”的结构,并且在其中有2d指针数组

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

I have an initializeFoo function like so that allocates memory for the whole object 我有一个initializeFoo函数,以便为整个对象分配内存

      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? 但是,由于我在运行程序时导致分段错误(核心转储),因此我认为我需要为* stuff分配内存,但是我该怎么做呢? And would I stick that in the initializeFoo function? 我可以将其保留在initializeFoo函数中吗?

My guess would be to use: 我的猜测是使用:

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

Can someone help me out? 有人可以帮我吗?

Yes you need to allocate memory for stuff . 是的,您需要为stuff分配内存。 Also, what you have now is actually a three-dimensional "array". 另外,您现在拥有的实际上是三维“数组”。

You also doesn't allocate enough memory for stuff . 您也没有为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 : 然后在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);
}

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. 可以肯定地说,我将需要查看所有代码,但是我的猜测是您传递给initializeFoo本身的双指针尚未分配。

For example, if you do: 例如,如果您这样做:

Foo ** foo;
initializeFoo(foo);

Your program will segfault because you dereference foo, which has not been allocated. 因为您取消引用尚未分配的foo,所以程序将出现段错误。 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. 并且您的程序仍然存在段错误,那么问题必须出在其他地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM