20130413

How to use malloc for 2d array dynamic memory allocation


/*How to use malloc for 2d array dynamic memory allocation. How to write 2-d array with dynamic memory allocation */
#include<stdio.h>
#include<malloc.h>
int main()
{
int r,c,i,j;
printf("Enter No of rows and columns:");
scanf("%d%d",&r,&c);

int **array;
array=(int**)malloc(r*sizeof(int));

for(i=0;i<r;i++)
{
array[i]=malloc(c*sizeof(int));
}


printf("\n Enter the elements 1 by 1:\n");

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&array[i][j]);
}
// printf("\t");

}
printf("You Entered:\n");

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d",array[i][j]);
printf("\t");
}
printf("\n");
}
printf("\n");

}

/*
* $ ./a.out
Enter No of rows and columns:4
4

Enter the elements 1 by 1:
1
2
3
4
5
6
7
8
8
8
8
8
1
1
1
1
You Entered:
1 2 3 4
5 6 7 8
8 8 8 8
1 1 1 1
Dynamic memory allocation for multi dimensional array here for 2-d ( two dimensional array).There are various ways to allocate memory dynamically for multi dimensional array:

1. Pointer to pointer
First memory is allocated for array which contains pointers to array to integers.
Then, memory is allocated for the each array pointed by the pointers.
Finally memory is de-allocated in the reverse order of the allocation.
Actually we allocate memory for number of rows and then columns.
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
It can be done by pointer to pinter to int.
example as above.
Int **array; //array is a pointer to pointer to int.
Array is a pointer to pointer to int. it means that array first points to pointers then in turn pointers point to integers. We need to allocate enough memory for the pointers to hold ponters to integers which nothing but memory for the rows. So dynamic memorty allocation for 2d array would be like this.

Previous                             Home                               Next

No comments:

Post a Comment