I want to create a bidimensional array that represents the positions of a board game. I've defined that each position is of type 'struct position' which is a enum that can be 'empty', 'piece1' or 'piece2'. The problem is that the user decides which size the table is, that is, how many positions the bidimensional array will have. Since I'm calling graphic functions of opengl which can't take ar开发者_开发百科guments (or is there a way for them to do that?), is it possible to define the size of the bidimensional array at runtime?
No, you can't define the size of an array at run-time in C. But one-dimensional arrays have the same semantics as pointers, so you can "emulate" a multi-dimensional by using pointers instead. Something like this should do the trick:
int w = 16, h = 16;
int *array = malloc(sizeof(int) * w * h);
int x = 4, y = 2;
array[y * w + x] = 1;
精彩评论