How to find size of an array in C without sizeof
arjunsreedharan.org
How to find size of an array in C without sizeof
1–10 of 212 posts
Re: How to find size of an array in C without sizeof
#2Quoting http://stackoverflow.com/a/16019052/1470607
Note that this trick will only work in places where `sizeof` would have worked anyway.Re: How to find size of an array in C without sizeof
#3C11 6.5.6/8:
If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated
Re: How to find size of an array in C without sizeof
#4Re: How to find size of an array in C without sizeof
#5Edit: Just to clarify, what you get is ptrdiff_t instead of size_t. So if array size is greater than PTRDIFF_MAX, you get undefined behavior [1].
Re: How to find size of an array in C without sizeof
#6http://stackoverflow.com/questions/671790/how-does-sizeofarr...
I think this is effectively doing the same thing, but in a non-standard way; ie. I think `int n = (&arr)[1] - arr;` is substituted with the actual the number by the compiler the same way sizeof() would be, only noone will know wtf is going on.
Disclaimer: I didn't look at the generated code to confirm; I guess it could even be compiler/runtime dependent.
Re: How to find size of an array in C without sizeof
#7Given how many bugs & errors stem from simple fails in range checks etc, I would much rather go with the tried and true way rather than use something "clever". Quoting http://stackoverflow.com/a/16019052/1470607 Note that this trick will only work in places where `sizeof` would have worked anyway.
Unless you're writing a buffer overflow exploit, in which case you need to know exactly what's on the stack and where, this isn't a good way to program.
Update: misread the article; thought he was differencing with the beginning of the next array.
Re: How to find size of an array in C without sizeof
#8Despite the argument at the end, this is undefined behavior in the latest C specification. The code dereferences a pointer one past the last element. C11 6.5.6/8: If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated
Re: How to find size of an array in C without sizeof
#9I haven't written C in a while, but I think this is pretty stupid. sizeof() is a compile-time thing in C, so it's substituted with a number by the time you get an executable. See: http://stackoverflow.com/questions/671790/how-does-sizeofarr... I think this is effectively doing the same thing, but in a non-standard way; ie. I think `int n = (&arr)[1] - arr;` is substituted with the actual the number by the compiler th…