Reputation: 541
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.
Upvotes: 3
Views: 11521
Reputation: 386
Is it possible to initialize a multi dimensional array without first initializing its size?
=> No, it is not possible.
The thing possible is that you take the size of the array and then allocate memory using calloc. I'm asking you to use calloc because this way all the array elements will be initially initialized as 0.
Now, use of calloc will be applied as:
Assuming you want 2D array, so you take variable row and column as input from the user. Then use,
int *x;
x = calloc( ( row * column), sizeof(datatype) );
In this case the datatype would be int.
In short code would appear as :
int row, column, *x;
/* TAKING INPUT FROM THE USER */
printf("\n\t Enter the number of rows : ");
scanf("%d", &row);
printf("\n\t Enter the number of columns : ");
scanf("%d", &column);
/* DYNAMICALLY ALLOCATING MEMORY TO x USING calloc */
x = calloc( (row * column), sizeof(int));
I hope this code solves your problem.
I have one more thing to share with you.
In your this line of code :
int x[][] = {{1,2,3},
{4,5,6}};
This initialization is just missing one thing and that thing is mention of column size and otherwise code is correct.
So, Correction to your code :
int x[][3] = {{1,2,3},
{4,5,6}};
This would work fine.
Keep on trying! These type of things can only be known while practicing.
Happy Coding!
Upvotes: 1
Reputation: 249153
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]
.
Upvotes: 5
Reputation: 1527
Yes, but you're missing a comma:
int x[2][3] = {{1,2,3},
{4,5,6}};
All array elements (even inner arrays) need to be comma-separated
Upvotes: -4