简体   繁体   English

在 C 中初始化结构指针的二维数组

[英]initializing a 2-D array of structs pointers in C

I'm using -std=gnu99 when I compile.我在编译时使用-std=gnu99 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:我注意到您可以像这样在堆中使用 NULL 值初始化一维结构数组:

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?当我去释放这个内存时,我会free() 10 次,还是 100 次? And what about the variable length of foo.quux?那么 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.因为您想为 Foo* 分配足够的空间,这将表示数组的开始。 The original line will allocate space for a Foo.原始行将为 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.如果您以上述样式分配 2D 数组,则总共需要执行 11 个 free(),一个用于分配的每个子数组 (10),一个用于分配的指针数组。 Ie IE

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

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

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