Pages

Wednesday, March 1, 2017

Dynamic memory allocation

Dynamic memory allocation means, programmer can manually handle memory space during runtime of programMalloc( ) function allocates requested size of bytes and returns a pointer to first byte of allocated memory.

Following program will demonstrate use of malloc() function for allocating memory at run time.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *ptr;

    //Following statement allocates 2 int size memory space
    ptr = (int*)malloc(2*sizeof(int));  
    
    if(ptr == NULL)                     
    {
        printf("Error during memory allocation.");
        exit(0);
    }

    printf("Enter your number1: ");
    scanf("%d", ptr);
    
    printf("Enter your number2: ");
    scanf("%d", ptr+1);
   
    printf("Your number1 = %d\n", *ptr);
    printf("Your number2 = %d", *(ptr+1));
    
    free(ptr); //allotted memory will be cleared.

    return 0;
}

Output of the program:

Enter your number1: 101
Enter your number2: 202
Your number1 = 101
Your number2 = 202


* * * * *

No comments:

Post a Comment