C Programming - Complicated Declarations - Discussion
Discussion Forum : Complicated Declarations - True / False Questions (Q.No. 5)
5.
We can allocate a 2-Dimensional array dynamically.
Discussion:
5 comments Page 1 of 1.
Utkarsh said:
5 years ago
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.
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.
Saps said:
1 decade ago
#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();
}
#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();
}
Sachin said:
1 decade ago
How ? Please explain more.
Sundar said:
1 decade ago
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 *));
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 *));
Andrew said:
1 decade ago
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
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
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers