Summary: This program allocates memory at runtime using malloc() to store marks of students. It calculates and displays the average of those marks, and properly frees the memory afterwards.
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
float *marks, sum = 0;
printf("Enter number of students: ");
scanf("%d", &n);
marks = (float *) malloc(n * sizeof(float));
if (marks == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
printf("Enter marks: ");
for (int i = 0; i < n; i++) {
scanf("%f", marks + i);
sum += *(marks + i);
}
printf("Average marks = %.2f\n", sum / n);
free(marks);
return 0;
}
Memory Allocation:
The program uses malloc() to dynamically allocate memory for storing student marks. This is necessary when the number of students is not known at compile time.
Pointer Arithmetic:
The program accesses elements using pointer arithmetic like *(marks + i) instead of array indexing.
Sum and Average:
As each mark is entered, it is immediately added to sum. The average is calculated by dividing the total sum by the number of students.
Memory Deallocation:
After usage, the memory is freed using free() to avoid memory leaks.