As is well known, arrays decay to pointers when passed as parameters in C. But an array of arrays only decays to a pointer of arrays; hence if we enclose our original array itself in an array, we can retrieve the original array length after passing the enclosing array into a function. Here's a program that tests this idea:
/* array_workaround.c */
#include <stdio.h>
void printsize(char array_pointer[][10]);
int main(void)
{
char a[10];
for(char i = 0; i < 10; i++)
a[i] = i;
char a_p[1][10] = {a};
printsize(a_p);
return 0;
}
void printsize(char array_pointer[][10])
{
printf("%lu\n", sizeof(array_pointer[0]));
}
When run, it prints out the correct value (10
), but the compiler gives this warning:
array_workaround.c:12:24: warning: incompatible pointer to integer conversion
initializing 'char' with an expression of type 'char [10]' [-Wint-conversion]
char a_p[1][10] = {a};
Of course, the issue with this "workaround" is that it requires that the size of the array be hard-coded into the function receiving it, which sort of defeats the whole purpose. However, it does mean that the array is checked to be of the right size, without having to pass in the length as a separate parameter... (as long as it's always 10! lol).
So what is going on with the warning? Is the compiler simply not "smart enough" to know that what is going on here doesn't corrupt any data? Or am I just getting lucky somehow? Can anyone see a way to make it an actual workaround so that you don't have to hard-code the number 10 in there?