我环顾四周,但未能找到解决这个问题的好方法。 这是我的代码:
#include <stdlib.h>
struct my_struct {
int n;
char s[]
};
int main()
{
struct my_struct ms;
ms.s = malloc(sizeof(char*)*50);
}
这是 gcc 给我的错误: 错误:灵活数组成员的使用无效
如果我在结构中声明 s 的声明,我可以让它编译
char* s
这可能是一个更好的实现(指针算法比数组快,是吗?) 但我想在 c 中声明
char s[]
与
相同char* s
最佳答案
你现在的写法,过去被称为“struct hack”,直到 C99 将其称为“灵活的数组成员”。你得到一个错误的原因(可能无论如何)是它需要跟一个分号:
#include <stdlib.h>
struct my_struct {
int n;
char s[];
};
当你为此分配空间时,你想要分配结构的大小加上你想要的数组空间量:
struct my_struct *s = malloc(sizeof(struct my_struct) + 50);
在这种情况下,灵活数组成员是一个 char 数组,并且 sizeof(char)==1,因此您不需要乘以它的大小,但就像您需要的任何其他 malloc 一样它是一些其他类型的数组:
struct dyn_array {
int size;
int data[];
};
struct dyn_array* my_array = malloc(sizeof(struct dyn_array) + 100 * sizeof(int));
编辑:将成员更改为指针会产生不同的结果。在这种情况下,您(通常)需要两个单独的分配,一个用于结构本身,一个用于指针指向的“额外”数据。使用灵活的数组成员,您可以在单个 block 中分配所有数据。
关于c - 如何在 C 中的结构中包含动态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2060974/