সমস্যা
ডাইনামিক মেমরি অ্যালোকেশন ফাংশন ব্যবহার করে এলিমেন্ট প্রদর্শন ও যোগ করার C প্রোগ্রাম লিখুন।
সমাধান
C-তে লাইব্রেরি ফাংশন malloc রানটাইমে বাইট 단위로 মেমরি ব্লক অ্যালোকেট করে। এটি একটি ভয়েড পয়েন্টার রিটার্ন করে যা অ্যালোকেটেড মেমরির বেস অ্যাড্রেসকে পয়েন্ট করে এবং মেমরিটি আনইনিশিয়ালাইজড রেখে দেয়।
সিনট্যাক্স
void *malloc(size in bytes)
উদাহরণ:
int *ptr; ptr = (int *) malloc(1000);int *ptr; ptr = (int *) malloc(n * sizeof(int));
দ্রষ্টব্য — মেমরি ফ্রি না থাকলে NULL রিটার্ন করে।
উদাহরণ
#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 Output - 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 45 65 12 23 The sum of elements is 168 Displaying the cleared out memory location : 10753152 0 10748240 0 23