c - 带指针使用的结构体,段错误

标签 c pointers struct segmentation-fault

我在 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/

相关文章:

c - 数组的 For 循环 - 从以前的值添加

c - vsnprintf 和 strerror : segmentfault?

php - 使用 PHP 调用 C 可执行文件

c - 为什么在将二维数组传递给函数时指定列大小

c - 字符指针数组函数如何实现?

python - "Struct arrays"

c++ - 是否需要在析构函数中删除指针?

c++ - C++中uint8_t *值的含义和调试(打印)

c - 包含 scanf 和 file 的结构

c - 声明中有两种或多种数据类型