Re:A nice, little known C feature: Static array indices in p...
by mauvehaus on Monday February 18, 2013 @03:46PM
(#5240533)
The compiler doesn't pass any size information when you pass an array into a function. The function just gets a pointer. If you take the sizeof the array, you'll get the size of a pointer on your system:
[eric@rangely foo]$ cat foo.c
#include <stdio.h>
int test (int arr[10])
{
printf ("%lu\n", sizeof (arr));
return 0;
}
int main (int argc, char *argv[])
{
int arr[5];
test (arr);
return 0;
}
[eric@rangely foo]$ gcc foo.c -Wall -o foo && ./foo8
(EDIT: fixed formatting)
Re:A nice, little known C feature: Static array indices in p...
by kelnos on Monday February 18, 2013 @03:55PM
(#5240582)
As another poster said, the compiler can't know inside the function body the size of the array passed if you just use sizeof.
More to a style/safety point, if I ever see a function that expects an array and doesn't also take the size of that array as another parameter, that's a bug waiting to happen.
Especially in this case since this feature seems to only throw a warning on recent versions of clang, and more or less nothing else.
Re:A nice, little known C feature: Static array indices in p...
by corysama on Monday February 18, 2013 @03:49PM
(#5240545)
Wouldn't you need to put your sizeof test outside of every call to your function? Inside the function it would only know the declared parameter's type, so it would have no idea what sized array you actually passed.
In the rare cases you need to do this sort of check why not just write a simple sizeof test?