I wanted to use the fact that &arr points to the complete arr and not just the first element, to calculate array length like this
int size = *(&arr + 1) - arr ;
Now this will work in main function but I want to calculate the size within a function in which array is not defined and takes arr as parameter.
As arr decays into a pointer when passed into a function. sizeof(arr)/sizeof(arr[0]) method does not work as it means
sizeof(int*) / sizeof(int)
// i.e. 4/4 = 1.
I wanted to use &arr method inside a function but that does not work too for some reason… which is why I wanted to pass &arr as a parameter inside the function. I tried simply pass it by writing &arr as a parameter, but I am confused what is the data type of &arr as it says expected
expected 'int *' but argument is of type 'int (*)[4]'
which is good as I am passing int(*)[4] only but how to specify this inside function parameter.
>Solution :
… to calculate the size within a function in which array is not defined and takes arr as parameter.
In C, when variable length arrays are available:
// The array is not defined here.
void bar(size_t n, int (*arg)[n]) {
// Size of the array from main() is calculated here.
size_t size = sizeof *arg / sizeof *arg[0];
printf("%p %zu\n", (void*) arg, size);
}
int main(void) {
// Array defined here.
int arr[42];
size_t sz = sizeof arr / sizeof arr[0];
bar(sz, &arr);
return 0;
}
Output
0xffffcbe0 42