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.

3 Answers 3

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.

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

2 Comments

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 :-)
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
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)

Comments

1

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

2 Comments

Yes. But you should also mention when to use what and which is better to use.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.