我想创建一个结构,但我也想用动态内存分配来编写它的数组或字符串元素。
struct st {
char *name[40];
int age;
};
对于“name”字符串,我应该在 struct 之前使用 malloc,还是我也可以在 struct 中使用它。
1)
char *name = malloc(sizeof(char)*40);
struct st {
char *name;
int age;
};
2)
struct st {
char *name = malloc(sizeof(char)*40);
int age;
};
两者都是真的还是有误?如果它们都为真,那么哪个对代码的其他部分更有用?
最佳答案
您需要创建结构的实例,它的实际变量。然后需要在函数中初始化结构体实例的成员。
例如,在某些功能中你可以做
struct st instance;
instance.name = malloc(...); // Or use strdup if you have a string ready
instance.age = ...;
关于c - C中struct中数组和字符串的动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37546479/