echelon


C99: casting to variable-length arrays

C99 understands variable-length arrays. They look something like this:

int d1, d2, d3, d4;
// runtime-assign those variables
int vla[d1][d2][d3][d3];

Now the question is, how to properly cast a pointer to this type when passing it to a function that accepts such a type in a way that makes the compiler happy? The syntax is somewhat unusual:

void func(int d1, int d2, int d3, int d4, int vla[d1][d2][d3][d4]){}
// ...
int * x = malloc();
func(d1, d2, d3, d4, (int (*)[(int)(d2)][(int)(d3)][(int)(d4)])x);

Tested with gcc 4.6.1 and the –std=c99 compiler option. I could not find information about this anywhere on the web so I hope this will help others who wonder how it should be done.



2 Comments

#1 mgaunard wrote on January 10, 2012:

I guess it’s a fairly nice way to cast a block of memory into a n-dimensional array.

#2 Sebastian Schaetz wrote on January 11, 2012:

C99 can be fairly nice sometimes – in it’s own way.

Sorry, the comment form is closed at this time.