我在 C 中使用结构数组时遇到了一些问题。它返回了段错误
struct Yset{
char *unit;
char *name;
char *showValue;
char *fillColor;
char *yData;
};
struct Yset *svg_ysets;
int ySetCounter = 0;
svg_ysets[ySetCounter].unit = malloc(strlen((char*)attribute)+1);
strcpy(svg_ysets[ySetCounter].unit,(char*)attribute);
printf("%s\n", svg_ysets[ySetCounter].unit);
ySetCounter++;
这样使用有什么问题吗?我不知道 Yset 的数量,所以它必须是动态的。谢谢
最佳答案
svg_ysets[ySetCounter].unit = malloc(strlen((char*)attribute)+1);
您取消引用结构体指针,而该指针没有指向有意义的位置。换句话说,您没有分配空间来保存结构对象本身。
// allocate five objects
struct Yset *svg_ysets = malloc (5 * sizeof(struct Yset));
如果您在某处使用动态分配的内存,请不要忘记释放
。
关于c - 带指针使用的结构体,段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35962106/