0% found this document useful (0 votes)
3 views

C-dynamic memory allocation

The document outlines a study on dynamic memory allocation in C, including its definition, advantages, and relevant functions. It provides a problem statement to write a program that dynamically allocates memory for an array of integers and calculates their average. The included code demonstrates the implementation of this program, handling memory allocation, user input, and output of the average.

Uploaded by

mgaana146
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C-dynamic memory allocation

The document outlines a study on dynamic memory allocation in C, including its definition, advantages, and relevant functions. It provides a problem statement to write a program that dynamically allocates memory for an array of integers and calculates their average. The included code demonstrates the implementation of this program, handling memory allocation, user input, and output of the average.

Uploaded by

mgaana146
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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;

You might also like