Tuesday, August 9, 2016

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


Many different implementations of the actual memory allocation mechanism, used by malloc(), are available. 
ScreenHunter_007
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


Read more at:
Learn to Code by Making Games - The Complete Unity Developer
The Complete Unity 5 Guide: Unity Game Development Made Easy
Unity3D - Master Unity By Building Games From Scratch



No comments:

Post a Comment