Dynamic Arrays in C-Programming Just like we can allocate run-time memory in C++
ID: 3831918 • Letter: D
Question
Dynamic Arrays in C-Programming Just like we can allocate run-time memory in C++ by using new and delete, we can allocate run-time memory in C Programming as well. For this, we use malloc( ) and/or calloc( ) functions to allocate memory. For example, int*ptr = (int*)malloc (10, sizeof(int)); This allocates space for a dynamic array of 10 integers. To deallocate this memory, we need to use the free( ) function. For example, free(ptr) Unlike with new and delete, if the allocate dynamic memory is not deemed sufficient, we can increase the allocated run-time memory. This is done via realloc( ) function. For example, ptr = realloc(ptr, 20*sizeof(int)); This statement now increases the allocated memory size to an array of 20 integers. Now, write a C-program that calculates the average of doubles. Your program will prompt the user for the value of double in a loop. The loop needs to terminate if the user decides there are no more numbers to enter. The user does not know how many numbers are there in total, so your allocated must grow as the user decides to enter more numbers. Initially, allocate run-time memory for one double only and obtain the value of the double from the user. In the loop, use the realloc( ) function to increase the memory allocated. Keep growing your memory and reading new double values as long as the user wants to enter new numbers. For every entry, you needs to update the sum and the average of the values entered by the user, and display the updated average. After writing the code, save it as LabEC_A.c. Compile and test it using the gcc compiler, not the g++ compiler and upload on Blackboard. Remember, you have to use printf( ) and scanf( ) for I/O, cin/cout will not work in C-programming.Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
int main()
{
double *arr = (double *)malloc(sizeof(double));
int size = 1;
int count = 0;
double sum = 0;
while(1)
{
double num;
printf("Enter a double value. -1 to stop entering: ");
scanf("%lf", &num);
if (num == -1)
break;
arr[count++] = num;
sum += num;
printf("Average so far %f ", sum/count);
if(count == size)
{
arr = (double *)realloc(arr, 2*size*sizeof(double));
size = size*2;
}
}
free(arr);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.