首页 > 解决方案 > 如何解释结构指针数组的这种行为?

问题描述

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

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

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

标签: carraysstruct

解决方案


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

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

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

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

现在,无论array何时,您都将分配正确的大小。


推荐阅读