Thursday, 15 March 2018

Malloc --> Dynamic Memory Allocation (Addition of Elements)

Dynamic Memory Allocation is a concept of C language that will allow you to create space in memory at run time.
Types of Dynamic Memory Allocation:-
Calloc
Malloc

Here a  simple program of malloc that will make it easy to understand .

/* Pre-Processor*/
#include<stdio.h>
#include<conio.h>
void main()
{
    int i,num,*ptr,sum=0;
    printf("Enter number of elements: ");
    scanf("%d",&num);
    ptr=(int *) malloc(num * sizeof(int));
    printf("Enter the elements of the array:-\n");
    for(i=0;i<num;i++)
    {
        scanf("%d",ptr+i);
        sum +=*(ptr+i);
    }
    printf("Sum=%d",sum);
    free(ptr);
}


No comments:

Post a Comment