I have seen the following declaration of two dimensional array.
int arr[][3] = { {1,2,3}, {4,5,6}};
My question is how can I allocate following multidimensional array in run time based on user input of first dimension?
#define M 10
#define N 15
int arr[][M][N]
asked Apr 19, 2018 at 0:52
2 Answers 2
Start by declaring a pointer suitable for accessing the array:
int (*array)[M][N];
Then allocate memory for the array based on the user input:
array = malloc(P * sizeof(*array)); // P is the value obtained from the user
Then use the pointer as if it was a 3D array:
array[x][y][z] = 42;
Don't forget to free the memory when you're done with it.
answered Apr 19, 2018 at 1:00
Sign up to request clarification or add additional context in comments.
2 Comments
aliceangel
Can you please explain these lines... int(*array)[M][N] and malloc. In malloc, what is the sizeof returns? the size of whole array or the size of int pointer?
user3386109
@userfirst785935
sizeof(array) is the size of a pointer, but sizeof(*array) is the size of an array of 150 ints. So if you try printf("%zu\n", sizeof(*array)), the output should be 600 (assuming an int is 4 bytes). When you multiply the 600 by the value provided by the user, the result is the number of bytes in the whole 3D array.C allows variable-length arrays. So after reading the first dimension from the user, you can declare the array with that size.
int n;
printf("How big is it? ");
scanf("%d", &n);
int arr[n][M][N];
answered Apr 19, 2018 at 1:14
2 Comments
phuclv
note that it's only allowed in C99, and optional in C11
Stargateur
@GRC VLA allow any level of nested array.
lang-c