I can get the sizeof an object in an array in a local function:
int xa[] = {3,5};
printf("Sizeof: %zu\n", sizeof(xa));
Sizeof: 8
But if I pass it to a function, I get a warning:
void sum_array(int x[]) {
int sum=0;
for (int i=0; i < (sizeof(x) / sizeof(*x)); i++ ) {
sum += x[i];
}
printf("%d\n", sum);
}
'sizeof' on array function parameter ‘x’ will return size of ‘int *’ [-Wsizeof-array-argument]
What's the reason that this occurs? I can suppress this by changing the formal parameter from int x[] to int* x, but I'd like to understand why this is occurring. My thought that was within a function parameter that type* x and type x[] were identical, but I guess I was mistaken.
int *.int x[]is passed to a function it goes tofunc(&x[0])? Is there any way to keep the size information then (such as to dosizeofor do you have to explicitly pass it another argument, such asint sizeto convey the original array dimensions?sizeofproduces a value OP did not expect but rather asks about the warning and the difference in compiler behavior between declaring the parameter as an array versus declaring it as a pointer.func(x)andfunc(&x[0])are equivalent. The size information is irrevocably lost when the array is passed to a function. See C11 §6.7.6.3 Function declarators (including prototypes) ¶7.sizeof(array). There are others, mostly not as widely approved of and many a duplicate of these. There are some questions dual tagged with both c and c++; I've not linked to those.