Dynamic Memory Allocation (Concept)

#include <stdio.h>
#include <stdlib.h>
/*
Dynamic Memory Allocation is used to make our code to take storage memory in heap section. It just make our code memory efficient. For ex. you have allocated an array[20] but you ended up using only 10 elements then the rest 10 space got wasted and couldnot be utilised further. But by using DMA, it allocates the memory only at run time.
*/
int main(){
    // Use of MALLOC:
    int n;
    printf("Enter the size of array: ");
    scanf("%d",&n);
    int* myarr;
    myarr= (int*)malloc(n*sizeof(int));

    for(int i=0;i<n;i++){
        printf("Enter element %d : ",i+1);
        scanf("%d",&myarr[i]);
    }
    for(int i=0;i<n;i++){
        printf("The value at index %d is %d\n",i,myarr[i]);
    }

    // Use of CALLOC:
    int n;
    printf("Enter the size of array: ");
    scanf("%d",&n);
    int* myarr;
    myarr= (int*)calloc(n,sizeof(int));
    
    for(int i=0;i<n;i++){
        printf("Enter element %d : ",i+1);
        scanf("%d",&myarr[i]);
    }
    for(int i=0;i<n;i++){
        printf("The value at index %d is %d\n",i,myarr[i]);
    }
/*
Difference between Malloc & Calloc is that when we dont input anything in calloc it returns 0 to that value whereas in malloc it return a garbage value.
*/   

    // Use of REALLOC:
    int m;
    printf("Enter the new size of array: ");
    scanf("%d",&m);

    myarr= (int*)realloc(myarr,m*sizeof(int));
    
    for(int i=0;i<m;i++){
        printf("Enter new element %d : ",i+1);
        scanf("%d",&myarr[i]);
    }
    for(int i=0;i<m;i++){
        printf("The new value at index %d is %d\n",i,myarr[i]);
    }
/*
Realloc just reinitialize the value of previous array if we dont input new values, previous values remain same.
*/
    return 0;
}

Comments

Popular Posts