gpt4 book ai didi

c - 如何解释结构指针数组的这种行为?

转载 作者:太空宇宙 更新时间:2023-11-04 00:16:05 24 4
gpt4 key购买 nike

我有一个结构指针数组,并将真正的学生分配给该数组。这是代码:

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;

}

它编译但给出输出

026082个3

代替

01个2个3

这里发生了什么?如何解决这个问题?

最佳答案

sizeof(s_ptr) 是一个指针的大小;不是结构的大小。

这是为什么类型定义指针(您的意思是用作指针)容易出错的另一个示例。

除此之外,您可以通过将 sizeof 应用于表达式来避免此类错误:

array = malloc(sizeof(*array) * 4);

现在,无论 array 指向什么,您都将分配正确的大小。

关于c - 如何解释结构指针数组的这种行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51968515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com