C Programming - Complicated Declarations - Discussion

5. 

We can allocate a 2-Dimensional array dynamically.

[A]. True
[B]. False

Answer: Option A

Explanation:

No answer description available for this question.

Andrew said: (Jun 18, 2010)  
The answer if False. A compiler can create a fixed 2-D array for example x[5][6] but you cannot do this in function eg

int *box(u32 Width , u32 Height)
{
static int *Area[Width][Height];
return Area;
}

Also the code compiled would not know how to access each element, where is Area[5][3] if the Area is 8,8 or 10,5

Sundar said: (Jun 19, 2010)  
Hi Andrew,

We can allocate a 2-Dimensional array dynamically.

Yes. We can, but we'll end up using pointers to pointers.

Ex: int **array = malloc(nrows * sizeof(int *));

Sachin said: (Sep 27, 2010)  
How ? Please explain more.

Saps said: (Oct 30, 2013)  
#include<string.h>
#include<stdio.h>
#include<malloc.h>
char a;
void main()
{
int i,j,**data,dim_x = 2,dim_y=2;

data = (int **) malloc(sizeof(int) * dim_x);
for (i = 0; i < dim_x; i++) {
data[i] = (int *) malloc(sizeof(int) * dim_y);
}

for (i = 0; i < dim_x; i++) {
for (j = 0; j < dim_y; j++) {
scanf("%d",&data[i][j] );
}
}
for (i = 0; i < dim_x; i++) {
printf("\n");
for (j = 0; j < dim_y; j++) {
printf("%d ",data[i][j]) ;
}
}
a = getch();

}

Utkarsh said: (Jun 1, 2019)  
2-d arrays are basically 1-d arrays.

2-d array:
[[1,2],[3,4],[4,5]] is basically stored in memory like | 1 | 2 | 3 | 4 | 4 | 5 | continuously.

1-d array:
[1,2,3,4,4,5] is also stored in exactly the same way | 1 | 2 | 3 | 4 | 4 | 5 | continuously.

So malloc() function can allocate continuous blocks of memory dynamically. For that function both arrays are same.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.