Casting pointer to memory buffer to pointer to VLA Casting pointer to memory buffer to pointer to VLA arrays arrays

Casting pointer to memory buffer to pointer to VLA


Yes, this is legit, and yes, the variably-modified type system is extremely useful. You can use natural array syntax to access a contiguous 2-D array both of whose dimensions were not known until runtime.

It could be called syntactic sugar as there's nothing you can do with these types that you couldn't do without them, but it makes for clean code (in my opinion).


I would say it is valid. The Final version of the C99 standard (cited on Wikipedia) says in paragraph 7.5.2 - Array declarators alinea 5 :If the size is an expression that is not an integer constant expression: ...each time it is evaluated it shall have a value greater than zero. The size of each instanceof a variable length array type does not change during its lifetime.

It even explicitely says that it can be used in a sizeof provided the size never changes : Where a sizeexpression is part of the operand of a sizeof operator and changing the value of thesize expression would not affect the result of the operator, it is unspecified whether or notthe size expression is evaluated.

But the standard also says that this is only allowed in a block scope declarator or a function prototype : An ordinary identifier (as defined in 6.2.3) that has a variably modified type shall haveeither block scope and no linkage or function prototype scope. If an identifier is declaredto be an object with static storage duration, it shall not have a variable length array type.

And an example later explains that it cannot be used for member fields, even in a block scope :

...void fvla(int m, int C[m][m]); // valid: VLA with prototype scopevoid fvla(int m, int C[m][m]) // valid: adjusted to auto pointer to VLA{    typedef int VLA[m][m]; // valid: block scope typedef VLA    struct tag {        int (*y)[n]; // invalid: y not ordinary identifier        int z[n]; // invalid: z not ordinary identifier    };...