Search code examples
carraysstructmallocallocation

Allocating array of structures with malloc


C - initialize array of structs

Hi, I have a question about this question (but I don't have enough rep to comment on one of the answers).

In the top answer, the one by @pmg, he says you need to do

student* students = malloc(numStudents * sizeof *students);

Firstly, is this equivalent to/shorthand for

student* students = malloc(numStudents * sizeof(*students));

And if so, why do you do sizeof(*students) and not sizeof(student)?

No one commented or called him out on it so I'm assuming he's write, and PLEASE go into as much detail as possible about the difference between the two. I'd really like to understand it.


Solution

  • Let's say you were not initializing students at the same time you declared it; then the code would be:

    students = malloc(numStudents * sizeof *students);
    

    We don't even know what data type students is here, however we can tell that it is mallocking the right number of bytes. So we are sure that there is not an allocation size error on this line.

    Both versions allocate the same amount of memory of course, but this one is less prone to errors.

    With the other version, if you use the wrong type in your sizeof it may go unnoticed for a while. But in this version, if students on the left does not match students on the right, it is more likely you will spot the problem straight away.