Vấn đề
Làm thế nào để hiển thị và tính tổng của n số bằng cách sử dụng hàm cấp phát bộ nhớ động trong ngôn ngữ C?
Giải pháp
Sau đây là chương trình C để hiển thị các phần tử và tính tổng của n số bởi người dùng bằng cách sử dụng các hàm cấp phát bộ nhớ động. Ở đây, chúng tôi cũng cố gắng giảm lãng phí bộ nhớ.
Ví dụ
#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// } }
Đầu ra
Khi chương trình trên được thực thi, nó tạo ra kết quả sau -
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