Home  >  Article  >  Backend Development  >  Explain dynamic memory allocation in C language with an example

Explain dynamic memory allocation in C language with an example

王林
王林forward
2023-09-09 08:53:06666browse

Explain dynamic memory allocation in C language with an example

Problem

Using C programming, find the sum of n numbers entered by the user using dynamically allocated memory.

Solution

Dynamic memory allocation enables C programmers to allocate memory at runtime.

The different functions we use to dynamically allocate memory at runtime include:

  • malloc() - allocates a block of memory at runtime.
  • calloc() - Allocates contiguous blocks of memory at runtime.
  • realloc() - Used to reduce (or extend) allocated memory.
  • free() - Releases previously allocated memory space.

The following C program is used to display elements and calculate the sum of n numbers.

Using dynamic memory allocation functions, we try to reduce the waste of memory.

Example

Demonstration

#include<stdio.h>
#include<stdlib.h>
void main(){
   //Declaring variables and pointers,sum//
   int numofe,i,sum=0;
   int *p;
   //Reading number of elements from user//
   printf("Enter the number of elements : ");
   scanf("%d",&numofe);
   //Calling malloc() function//
   p=(int *)malloc(numofe*sizeof(int));
   /*Printing O/p -
   We have to use if statement because we have to check if memory
   has been successfully allocated/reserved or not*/
   if (p==NULL){
      printf("Memory not available");
      exit(0);
   }
   //Printing elements//
   printf("Enter the elements : </p><p>");
   for(i=0;i<numofe;i++){
      scanf("%d",p+i);
      sum=sum+*(p+i);
   }
   printf("</p><p>The sum of elements is %d",sum);
   free(p);//Erase first 2 memory locations//
   printf("</p><p>Displaying the cleared out memory location : </p><p>");
   for(i=0;i<numofe;i++){
      printf("%d</p><p>",p[i]);//Garbage values will be displayed//
   }
}

Output

Enter the number of elements : 5
Enter the elements :
23
34
12
34
56
The sum of elements is 159
Displaying the cleared out memory location :
12522624
0
12517712
0
56

The above is the detailed content of Explain dynamic memory allocation in C language with an example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete