Showing posts with label dynamic memory allocation in C. Show all posts
Showing posts with label dynamic memory allocation in C. Show all posts

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));
}

20120728

Simple Program for malloc in C

How to use malloc in C. Simple Program for malloc in C.

->malloc function allocates required amount of memory in heap (instead of stack) and
returns the pointer to the address of allocated block of memory.
->We need to type cast the returned pointer by malloc as it returns a void pointer.
->memory allocated by malloc in heap is deallocated by free, so that memory in heap can be
  allocated by other malloc functions.
->Syntax of malloc in C
datatype *p;
p=(datatype *)malloc(sazeof(datatype));
example of malloc:
int *p;
p=(int *)malloc(100*sizeof(int));

Explanation:
Here, malloc function allocates 400( 100*size of integer ie 100*4=400 ) bytes in heap and
assigns the address of the allocated memory in integer pointer p.
How to use malloc in C.
Simple Program for malloc in C.
#include<stdio.h>
int main
{
int *p;
p=(int *)malloc(sizeof(int));
*p=10;
printtf("%d",*p);
free(p);
return 0;
}
Previous                             Home                               Next