Wednesday, December 11, 2013

Dynamic Memory Allocation in C


Hi,
In this, I would like to post the program that was given for my juniors in my school. They were very new to Programming and I was standing there helping them sot out their problems while implementing it. They were asked to implement a 2D Dynamic Array. I tried to explain them as far as I could in this blog. Below is the explanation of the concept behind 2D Dynamic Array Creation.
Dynamically, if we wanna create anything, we have to go for "Pointers". Pointers  are capable of storing memory locations. We can create memory locations of our desired size dynamically and assign them to pointers. So, a pointer can very well suit our dynamic needs.
Below is a program fragment for creating 2d dynamic array. The Program actually is meant for our Juniors in Lab. They were asked to implement a 2d dynamic array for constant rowsize and variable column size.
source code:
#include<stdio.h>
#include<malloc.h>
int main(){
int **p; int i, j, x,y[10],tmp;
printf("Enter Rowsize x");
scanf("%d",&x);
//user-casting the null pointer for
//the demanded amount of memory, here, "x" many
//memory locations are created and the starting
//address of the first memory location is returned via
// a null pointer. This is assigned to the pointer
//for the pointer
p = (int **)malloc(x*sizeof(int *));
printf("Enter varying ColumnSize for each row");
for(i=0;i<x;i++)
{
printf("nrow%d:",i+1);
scanf("%d",&y[i]);
//pointer for the column data *(p+i)
//has to be the size of the column data
//y[i] many memory locations of size
//int (2 bytes) is created and the starting
//address is returned via a null pointer
//which is user-casted and used
p[i]= (int *)malloc(y[i]*sizeof(int *));
}
printf("nEnter elementsn");
for(i=0;i<x;i++)
for(j=0;j<y[i];j++){
scanf("%d",&tmp);
p[i][j] = tmp;
}
printf("nEntered elementsn");
for(i=0;i<x;i++){
for(j=0;j<y[i];j++)
printf("%dt",p[i][j]);
printf("n");
}
return 0;
}

That's it
Happy Exploring :)

No comments:

Post a Comment