Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ตัวอย่างโปรแกรมฟังก์ชั่นการจัดสรรหน่วยความจำแบบไดนามิกในภาษา C


ปัญหา

วิธีการแสดงและคำนวณผลรวมของตัวเลข n โดยใช้ฟังก์ชันการจัดสรรหน่วยความจำแบบไดนามิกในภาษา C

วิธีแก้ปัญหา

ต่อไปนี้เป็นโปรแกรม C เพื่อแสดงองค์ประกอบและคำนวณผลรวมของตัวเลข n โดยผู้ใช้โดยใช้ฟังก์ชันการจัดสรรหน่วยความจำแบบไดนามิก ที่นี่เรายังพยายามลดการสูญเสียหน่วยความจำ

ตัวอย่าง

#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 : \n");
   for(i=0;i<numofe;i++){
      scanf("%d",p+i);
      sum=sum+*(p+i);
   }
   printf("\nThe sum of elements is %d",sum);
   free(p);//Erase first 2 memory locations//
   printf("\nDisplaying the cleared out memory location : \n");
   for(i=0;i<numofe;i++){
      printf("%d\n",p[i]);//Garbage values will be displayed//
   }
}

ผลลัพธ์

เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −

Enter the number of elements: 4
Enter the elements:
23
45
67
89
The sum of elements is 224
Displaying the cleared out memory location:
7410816
0
7405904
0