Zaibis Zaibis - 8 days ago 6
C Question

Is this code well defined by using sizeof operator?

#include <stdio.h>

void test(int arr[]);

int main ()
{
int *arr[3];
int ar1[2] = { 1, 2 };
int ar2[3] = { 3, 4, 5 };
int vla[ar2[1]];
arr[0] = ar1;
arr[1] = ar2;
arr[2] = vla;

for (int i = 0; i < 3; i++)
{
test(arr[i]);
}
}

void test(int arr[])
{
printf("%zu\r\n", sizeof(arr));
}


As the title say: is this valid? and if so, is there a way to make
test()
output different values by using
sizeof
on function argument handed in like on array?

Answer

Yes it is valid and will give the size of an int pointer (that's what the type of the arr parameter is, there are no array parameters in C) in bytes. 1

To get the size of an array in bytes with sizeof, the argument has to be an actual array, not a pointer.

Consequently, it's not possible to get the size of an array passed as a parameter inside a function without passing an extra parameter specifying the size.

So,

is there a way to make test() output different values by using sizeof on function argument handed in like on array?

no. (Without editing the function body.)

1 If you're wondering how it's possible to pass an array as a pointer parameter, it's because of the implicit array-to-pointer conversion, known as array decaying.

Comments