Comrade_Comski Comrade_Comski - 1 month ago 12
C Question

Initializing a 2d array without specifying size

I can initialize a one dimensional array in c with or without initializing its size:

int x[] = {1,2,3,4,5};
int y[5] = {1,2,3,4,5};


But, when I try to do the same for a two dimensional array such as

int x[][] = {{1,2,3},
{4,5,6}};


I get an
error: array type has incomplete element type
. The same error occurs if I declare and initialize the array on different lines.
However, I can initialize it while stating the size:

int x[2][3] = {{1,2,3},
{4,5,6}};


There is no error with this one.
My question is, is it possible to initialize a multi dimensional array without first initializing its size? I ask this because for an eventual project, I need to be able to declare arrays and initialize them later, and their size will not be known when compiling.

Answer Source

is it possible to initialize a multi dimensional array without first initializing its size?

No, not in the way you are proposing or anything similar to that.

I need to be able to declare arrays and initialize them later, and they will have dynamic sizes.

If the size is unknown at compile time, you should allocate the array using a = malloc(x * y * sizeof(value_t)). Then index into it like a[i + j*y].