1

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

3

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

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?
@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.
0

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

note that it's only allowed in C99, and optional in C11
@GRC VLA allow any level of nested array.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.