AIM: To study dynamic memory allocation in C
Theory:
Define dynamic memory allocation
Advantageous of dynamic memory allocation
Explain Dynamic memory allocation functions in C
Problem Statement:
Write a program to dynamically allocate memory for an array of integers and calculate their
average.
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
int *arr;
int sum = 0;
float average;
// Input the number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Dynamically allocate memory for the array
arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
// Input the elements of the array
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
// Calculate the sum of the elements
for (int i = 0; i < n; i++) {
sum += arr[i];
// Calculate the average
average = (float)sum / n;
// Display the average
printf("\nThe average of the array elements is: %.2f\n", average);
// Free the allocated memory
free(arr);
return 0;