c - 如何解释结构指针数组的这种行为?
问题描述
我有一个结构指针数组并将真正的学生分配给该数组。这是代码:
struct student {
char* firstName;
char* lastName;
int day;
int month;
int year;
};
typedef struct student* s_ptr;
int main(int argc, char **argv) {
s_ptr array = malloc(sizeof(s_ptr) * 4);
int x;
for (x = 0; x < 4; x++) {
struct student newStudent = { "john", "smith", x, x, x };
array[x] = newStudent;
}
printf("%d ", array[0].day);
printf("%d ", array[1].day);
printf("%d ", array[2].day);
printf("%d ", array[3].day);
return 0;
}
它编译但它给出了输出
0 2608 2 3
代替
0 1 2 3
这里发生了什么事?如何解决这个问题?
解决方案
sizeof(s_ptr)
是指针的大小;不是结构的大小。
这是类型定义指针(您的意思是用作指针)容易出错的另一个示例。
除此之外,您可以通过应用于sizeof
表达式来规避此类错误:
array = malloc(sizeof(*array) * 4);
现在,无论array
何时,您都将分配正确的大小。
推荐阅读
- python - 在 Python 中检查 CSV 的第一个单元格是否为空白
- swift - SwiftUI 中来自 BindableObject 的去抖动方法调用
- excel - 打开文档或更新时执行代码(填充列表框)?
- android - 带有 RecyclerView 项的 LinearLayout 与 ConstraintLayout
- c# - 如果集合项的属性发生更改,则 WPF 调用转换器
- python - Keras 预测挂在 Heroku 上的 graph.as_default() 内
- scala - Scala - 如何过滤嵌套的集合结构?
- tensorflow - Keras 卷积选项“channels_first”是否适用于 Tensorflow?
- java - 如何将 ThreadLocal 从父线程复制到多个子线程?
- powershell - Powershell 导入-csv 错误