1

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.

Community
  • 1
  • 1
user3475234
  • 1,503
  • 3
  • 22
  • 40

3 Answers3

2

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.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • I actually prefer `sizeof(*students)` to make it clear that you're not doing another multiply and so as to not have to worry about the distinction between sizeof'ing a type and a variable :-) – paxdiablo Mar 31 '14 at 04:57
  • I prefer the first one, to make it clear that it is an expression following, not a *type*. Not an issue if you have good naming conventions, but that's not always the case – M.M Mar 31 '14 at 05:00
2

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)
Elad Levin
  • 355
  • 2
  • 7
1

There is no difference between the two. You can check it by yourself also by printing their sizes.

Meghan
  • 303
  • 2
  • 6
  • 17
  • Yes. But you should also mention when to use what and which is better to use. – HelloWorld123456789 Mar 31 '14 at 04:51
  • it's your choice actually. Both are just returning you the size of struct. However it you use *students , it helps in easier error checking(by you, not by the compiler) as others mentioned. But I generally use **sizeof(type)** not **sizeof(*ptr_to_struct)** but both are absolutely right. – Meghan Mar 31 '14 at 05:16