I was arguing with one of my friends, if we have defined an array/pointer:
sometype * p;
if we want to know the size of the type, he said one should use:
sizeof(sometype)
I said one could also use:
sizeof(p[0]),
it should be the same. He disagreed, and his point is if p
is not initialized, then this usage of p[0]
may cause problems.
But to my knowledge, only when we change or depend on the value of p[0]
, will this be harmful. Since we don't change p[0]
nor use p[0]
's value, this is totally sensible.
Since we can't persuade each other, can anyone make this concept clear.
I know this question is of no use, and almost all the developers will use sizeof(sometype), including me :). But this question is fun and I'm really curious to know if there is any case that sizeof(p[0]) will be harmful.
=================================
Let me extend this question a little bit. If I do use some irrelevant value (or considered as kind of random or whatever). Can I always use p[0]
to get a value?
To make the question more clear, If I don't change the value of an uninitialized pointer, just use the value it is pointing to, can I always get a value without causing problems?
The argument to sizeof
is an unevaluated operand, so pointer dereferences and so forth don't have to refer to valid memory. It's purely based on type information.
(As a corollary, sizeof *p
is not polymorphic, it uses the static type only.)
sizeof
is evaluated at compile-time so it does not matter whether the memory is initialized or not since that's a runtime thing.
So sizeof p[0]
or - what I think is even nicer since it does not look array-ish - sizeof *p
is a great way to avoid typing the type again when using sizeof
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With