C Code Snippets 9 - Dynamic Memory Allocation: malloc()



Hello everyone, 
Many different implementations of the actual memory allocation mechanism, used by malloc(), are available. 
Their performance varies in both execution time and required memory. Today, we are going to see an example that show the usage of malloc() function in C language.




/**
* Author : Berk Soysal
*/

#include <stdio.h>
#include <stdlib.h>

int main(){
    //declare variables
    int n,i,*ptr,sum=0;
    //get number of elements from the user
    printf("Enter number of elements: ");
    scanf("%d",&n);

    //memory allocation using malloc()
    ptr=(int*)malloc(n*sizeof(int));  

    //check if malloc returns NULL or not
    if(ptr==NULL)
    {
        printf("Error! memory not allocated.");
        exit(0);
    }

    //get elements of the array from the user
    printf("Enter %d integer values: ",n);
    for(i=0;i<n;++i)
    {
        scanf("%d",ptr+i);
        sum+=*(ptr+i);
    }
    printf("Sum=%d",sum);

    /* FREE the pointer so the allocated address
       can be used by other variables !!! important ! */
    free(ptr);
    return 0;
}


Output



Keywords: CCode Snippets
Author:

Software Developer, Codemio Admin

Disqus Comments Loading..