c - 访问动态分配的 C 结构数组时出现段错误
问题描述
我有以下以下列方式定义的结构
typedef struct _abcd {
int a;
unsigned long b;
void (*c)(int);
int d;
} abcd_t, *abcd;
现在我有以下代码
static abcd foo
int set_size(int size){
foo = malloc(sizeof(abcd) * size);
}
由于某种原因,此代码在访问数组成员的某些属性时给了我段错误。但我注意到,如果我将 malloc 行更改为以下内容 - 它可以解决问题
foo = malloc(sizeof(foo[0]) * size);
我觉得很奇怪很明显sizeof(foo[0]) = sizeof(abcd)
那么这里到底有什么区别?
谢谢
解决方案
obviously
sizeof(foo[0]) = sizeof(abcd)
It is not the same since you typedef
ed abcd
to be a *pointer* to struct _abcd
.
Use
foo = malloc(sizeof(*foo) * size);
to have robust code even if the type of foo
should change at some point.
Your
foo = malloc(sizeof(foo[0]) * size);
is essentially the same since foo[0]
is just syntactic sugar for *(foo + 0)
which becomes *foo
.
推荐阅读
- java - 如何从Java子目录中的类创建对象
- scala - 如何将 Flink DataSet 元组转换为一列
- c# - 在启动时设置 cookie (MVC .Net Core)
- java - 如何在相同的比较方法中也对名字进行排序
- android - 用于音频设备的 Android 蓝牙配对
- elasticsearch - Logstash 是否维护注册表文件?
- c# - 创建一个自定义属性,提示 Resharper 隐式使用该属性
- angular - 如何以反应形式为动态选择设置不同的值
- mercurial - 为什么 hg commit 创建一个新的头?
- php - 在前端自定义产品尺寸输出+更改尺寸标题