简体   繁体   English

在C中访问灵活数组成员

[英]Accessing a Flexible array Member in C

I have a struct that looks like this: 我有一个看起来像这样的结构:

typedef struct TestCase TestCase;
typedef struct TestCase {   
    char * userName;
    TestCase *c[];    // flexible array member
} TestCase;

And in another File I'm trying to set the flexible array member to NULL, but this doesn't seem to work (I'm not allowed to change how it's been defined) 在另一个文件中,我试图将灵活数组成员设置为NULL,但这似乎不起作用(不允许更改其定义方式)

void readIn(FILE * file, TestCase ** t) {
    *t = malloc(sizeof(TestCase));

    (*t)->c = NULL; //gives the error

}

I'm using double pointers because that's what's been specified for me (This isn't the entire code, but just a snipit). 我正在使用双指针,因为这是为我指定的(这不是完整的代码,而只是一个snipit)。 (As there is also code later to free the variables allocated). (因为稍后还有代码可以释放分配的变量)。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Take a look at this line: 看一下这一行:

 (*t)->c = NULL;

This tries to assign NULL to an array, which isn't allowed. 这会尝试将NULL分配给数组,这是不允许的。 It would be like writing something like this: 就像写这样的东西:

int array[137];
array = NULL; // Not allowed

When you have a flexible array member, the intent is that when you malloc memory for the object, you overallocate the memory you need to make room for the array elements. 当你有一个灵活的阵列成员,其目的是,当你malloc内存为对象,你overallocate内存,你需要腾出空间给数组元素。 For example, this code 例如,此代码

*t = malloc(sizeof(TestCase) + numArrayElems * sizeof(TestCase*));

will allocate a new TestCase which has an array of numArrayElems pointers. 将分配一个新的TestCase ,它具有一个numArrayElems指针数组。

If you don't know in advance how many pointers you'll need, then you probably should switch away from using flexible array members and just use normal pointers. 如果您事先不知道需要多少个指针,那么您可能应该放弃使用灵活的数组成员,而只使用普通的指针。

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

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