সমস্যা
কিভাবে সি ভাষায় গতিশীল মেমরি বরাদ্দকরণ ফাংশন ব্যবহার করে n সংখ্যার যোগফল প্রদর্শন এবং গণনা করবেন?
সমাধান
নিম্নলিখিত উপাদানগুলি প্রদর্শন করার জন্য এবং গতিশীল মেমরি বরাদ্দকরণ ফাংশন ব্যবহার করে ব্যবহারকারী দ্বারা 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