How can this behaviour of an array of struct pointers be explained?

时间:2018-08-22 13:55:52

标签: c arrays struct

I'm having an array of struct pointers and assign real students to the array. Here's the code:

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;

}

It compiles but it gives the output

0 2608 2 3

instead of

0 1 2 3

What's happening here? How to fix this?

1 个答案:

答案 0 :(得分:12)

sizeof(s_ptr) is the size of a pointer; not the size of a structure.

This is another example of why typedefing pointers (that you mean to use as pointers) is error prone.

Beyond that, you can circumvent such errors by applying sizeof to an expression:

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

Now, whatever array points at, you will allocate the correct size.