A normal way to get the length of an array is to use sizeof(a)/sizeof(a[0])
, for example:
for(j = 0; j < sizeof(a)/sizeof(a[0]); j++ )
do_something_with(a[j]);
however there's a risk if a
is just a pointer:
int *a = calloc(1, sizeof(int));
for(j = 0; j = sizeof(a)/sizeof(a[0]); j++ )
do_something_with(a[j]);
then one might get this to loop two times which is bad (if you're lucky sizeof(int*) and sizeof(int) is the same and it will only be one round).
Is there a way to create this macro such that it fails if a
is not of array type? The reason it need to fail is that if a
is not an array, but a pointer there's no safe way to determine the length of the vector (and certainly sizeof(a)/sizeof(a[0])
might result in a out of bound access).