Home > Backend Development > C++ > body text

Explain dynamic memory allocation in C language with an example

王林
Release: 2023-09-09 08:53:06
forward
623 people have browsed it

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//
   }
}
Copy after login

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!