সমস্যা
ডাইনামিক মেমরি অ্যালোকেশন ফাংশন ব্যবহার করে n সংখ্যা প্রদর্শন এবং যোগফল গণনা করা।
সমাধান
malloc() ফাংশন ব্যবহার করে মেমরি ডাইনামিক্যালি অ্যালোকেট করা হয় এবং free() দিয়ে মুক্ত করা হয়।
উদাহরণ প্রোগ্রাম
#include<stdio.h>
#include<stdlib.h>
void main() {
int numofe, i, sum = 0;
int *p;
printf("Enter the number of elements : ");
scanf("%d", &numofe);
p = (int *)malloc(numofe * sizeof(int));
if (p == NULL) {
printf("Memory not available");
exit(0);
}
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);
printf("\nDisplaying the cleared out memory location : \n");
for(i=0; i<numofe; i++)
printf("%d\n", p[i]); // গার্বেজ ভ্যালু দেখাবে
}
আউটপুট
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