1

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?

8
  • 8
    The reason is karma. You are getting punished by the universe for hiding a pointer behind a typedef. Commented Aug 22, 2018 at 14:02
  • I wouldn't say you shouldn't never do it. You can do your programming in whatever style you like, just be mindful and responsible for the choices. Hiding a pointer in a typedef is perfectly fine. Usually when that's used to encapsulate a data structure then one could also provide functions to initialize such structure properly so the end user of it doesn't have to mess with the internals. Also, functions to deallocate the data are equally handy. Commented Aug 22, 2018 at 14:08
  • There is another thing going on here. You say you are having an array of struct pointers. You are not. And again, if you didn't hide your pointer type behind a typedef, it would be much easier to see. Commented Aug 22, 2018 at 14:09
  • Try this: s_ptr array = malloc(sizeof(struct student) * 4); You'll be allocation enugh space for 4 students, not 4 pointers !! Commented Aug 22, 2018 at 14:11
  • 4
    @sidyll Regarding encapsulating a data structure: no, I would still not hide a pointer behind a typedef, because then the programmer thinks that they need to pass on a HANDLE* to functions, while HANDLE is actually enough. This adds needless obfuscation and makes debugging more difficult. I don't even hide function pointer typedefs behind pointers, but typedef a function type instead. Commented Aug 22, 2018 at 14:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.