Dynamic Memory Allocation
Dynamic Memory Allocation
Problem
• As you know, an array is a collection of a fixed number of
values. Once the size of an array is declared, you cannot change
it.
int A[5];
[0] [1] [2] [3] [4]
A 10 20 30 40 50
24 8 bytes 256 35
1010 1012 1020 1022 1024 1026
a 1012
Program: array of elements are stored in dynamically allocated
#include <stdio.h> memory using malloc()
#include <stdlib.h>
void main()
{
int *ptr, n, i;
printf(“enter the number of elements\n”);
scanf(“%d”,&n);
ptr=(int *) malloc(n*sizeof(int));
printf(“Enter %d elements\n”,n);
for(i=0;i<n;i++)
{
scanf(“%d”,ptr);
ptr++;
}
printf(“contents of array are\n”);
for(i=0;i<n;i++)
{
printf(“%d\t”,*ptr);
ptr++;
}
}
calloc()
• calloc()allocates memory for array elements and returns a
pointer to memory. (i.e) allocates multiple blocks of memory of
specified size. It initializes each block with a default value ‘0’.
• Syntax:
ptr_name =(data_type *) calloc (n, size);
where, n is number of memory blocks
size is size of each block in bytes
Example:
int *a;
a= (int *)calloc(4,2);
0 0 0 0
1010 1012 1014 1016 1018 1020 1022 1024 1026
a 1012
Program: array of elements are stored in dynamically allocated
#include <stdio.h> memory using calloc()
#include <stdlib.h>
void main()
{
int *ptr, n, i;
printf(“enter the number of elements\n”);
scanf(“%d”,&n);
ptr=(int *) calloc(n, sizeof(int));
printf(“Enter %d elements\n”,n);
for(i=0;i<n;i++)
{
scanf(“%d”,&ptr[i]);
}
printf(“contents of array are\n”);
for(i=0;i<n;i++)
{
printf(“%d\t”,ptr[i]);
}
}
realloc()
• realloc() is used to dynamically change the memory allocation
of a previously allocated memory.
a 1012
NULL
0 0 0 0
1010 1012 1014 1016 1018 1020 1022 1024 1026
a 1012
NULL
Program: De-allocating memory
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, *ptr1, n=5, i;
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);