As I understand it every VLA have an hidden variable of it's size which value can be 'acquired' by sizeof
operator. What I don't get here is pointer to VLA's used in function parameters - why isn't their size automatically deduced and stored in this hidden variable - why we should explicitly provide it. And in this case why should we even use it given that we have already the type 'pointer to array of unknown size'?
What I mean is this:
void func(size_t, int (*)[*]); //function accepting pointer to VLA
void func_1(size_t, int (*)[]); //function accepting pointer to array of unknown bound
void func(size_t sz, int (*parr)[sz]) //implementation of 'func'
{
printf("%lu", sizeof(*parr) / sizeof(int));
printf("%lu", sz);
}
void func_1(size_t sz, int(*parr)[]) //implementation of 'func_1'
{
//printf("%lu", sizeof(*parr) / sizeof(int)); //error: invalid application of 'sizeof' to an incomplete type 'int []'
printf("%lu", sz);
}
As I can see it the only benefit of using 'func' instead of 'func_1' is that 'sizeof' operator will return a copy of the initial value of 'sz'.
Example usages of the above functions:
int main()
{
size_t sz = 3;
int arr[sz];
func(sizeof(arr) / sizeof(int), &arr);
func_1(sizeof(arr) / sizeof(int), &arr);
return 0;
}
Why can't the size of pointer to VLA parameter be assigned implicitly? This would at least make some good use of the syntax:
void func(int (*parr)[*]) // size copied from function argument
{
printf("%lu", sizeof(*parr) / sizeof(int));
printf("%lu", sz);
}
And then calling the function like this:
int main()
{
size_t sz = 3;
int arr[sz];
func(&arr);
return 0;
}
Will cause array hidden size variable with value of '3' to be passed as hidden argument to 'func' creating code similar to instancing previous 'func' with current syntax and using 'sizeof' operator to passed array.
If you're curios enough compiling the proposed syntax into whatever Clang compiler - you'll get an easter egg (;.