সমস্যা
C প্রোগ্রামিং ব্যবহার করে গতিশীলভাবে বরাদ্দ করা মেমরি ব্যবহার করে ব্যবহারকারী দ্বারা প্রবেশ করা n সংখ্যার যোগফল খুঁজুন।
সমাধান
ডায়নামিক মেমরি বরাদ্দ সি প্রোগ্রামারদের রানটাইমে মেমরি বরাদ্দ করতে সক্ষম করে।
বিভিন্ন ফাংশন যা আমরা রান টাইমে গতিশীলভাবে মেমরি বরাদ্দ করতে ব্যবহার করি তা হল −
- malloc () - রানটাইমে বাইটে মেমরির একটি ব্লক বরাদ্দ করে।
- calloc () - রান টাইমে মেমরির ক্রমাগত ব্লক বরাদ্দ করা।
- realloc () − বরাদ্দ করা মেমরি কমাতে (বা) প্রসারিত করতে ব্যবহৃত হয়।
- ফ্রি () − পূর্বে বরাদ্দ করা মেমরি স্পেস ডিললোকেট করে।
নিম্নলিক 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 : 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