Reputation: 1573
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.
Upvotes: 1
Views: 186
Reputation: 355
http://en.wikipedia.org/wiki/Sizeof#Use
You can use sizeof with no parentheses when using it with variables and expressions. the expression
*students
is derefencing a pointer to a student struct, so
sizeof *students
will return the same as
sizeof(student)
Upvotes: 2
Reputation: 305
There is no difference between the two. You can check it by yourself also by printing their sizes.
Upvotes: 1
Reputation: 141544
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.
Upvotes: 2