Wednesday, January 17, 2018

Example C program for dynamic memory allocation

Example C program that uses dynamic memory allocation, Learn dynamic memory allocation

Dynamic memory allocation

//Program to sum num number of integers by allocating memory dynamically
#include <stdio.h>
#include <stdlib.h> //To be included to use malloc() function

int main()
{
    int num, i, *ptr, sum = 0;

    printf("Enter number of elements: ");
    scanf("%d", &num);

/* The function malloc(sizeof(int)) will allocate raw memory for storing something of size equivalent to an integer value. The following statement allocates memory for storing num numbers. Hence sizeof(int) is multiplied by num. The (int *) will convert the allocated raw memory for storing integer values (type casting). */

    ptr = (int*) malloc(num * sizeof(int)); 

    if(ptr == NULL)         //if ptr==NULL means if memory cannot be allocated for some reasons
    {
        printf("Error! memory not allocated.");
        exit(0);                   // Close the program
    }

    printf("Enter elements of array: ");
    for(i = 0; i < num; ++i)
    {
        scanf("%d", ptr + i); //reads the value for summing
        sum += *(ptr + i); //the input numbers are added with the variable sum and stored in sum
        printf("%d", ptr+i);
    }

    printf("Sum = %d", sum);
    free(ptr); //To free the memory occupied by our program. It is not mandatory for our program
    getch();
    return 0;
}


**************












Featured Content

Multiple choice questions in Natural Language Processing Home

MCQ in Natural Language Processing, Quiz questions with answers in NLP, Top interview questions in NLP with answers Multiple Choice Que...

All time most popular contents

data recovery