I need help. I need to use heap memory for this program but I am not sure where
ID: 3781272 • Letter: I
Question
I need help. I need to use heap memory for this program but I am not sure where to use the malloc() function to allocate a set amount of heap memory. I think I can use either array or pointer notation to access the allocated memory but am not sure. I know that the program needs to free the allocated space before exiting.
This is the code currently:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int percentArray[50];
int percentage;
int count=0,i;
for(count=0; count<50; count++)
{ //for loop to read the grades till array size
printf("-------------------Enter percentage--------------- Add marks(a) Quit(q) ");
scanf("%c",&choice);
if(choice == 'a')
{ //if user choice is a, then read the grade
printf( "Enter grade:");
scanf("%d", &percentage);
getchar();
percentArray[count] = percentage; //add the grade to array
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
printf("Grades are: ");
for(i=0; i<count; i++)
{
printf("%d ", percentArray[i]); //print grades
}
printf(" ");
return 0;
}
Here are the directions: Modify the gradebook code so that it uses heap memory to store percentage grades in the range from 0 to 100 (inclusive). The program should allow the user to indicate when he or she is done entering grades (since the user may not have grades to fill the whole array). When the user is done entering grades, the program should print out the grades entered by the user. Be sure to free the head memory before the program ends.
Explanation / Answer
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int percentage;
int count=0,i;
//use the malloc() function to allocate heap memory for max 50 grades
int *percentArray = (int *) malloc (50*sizeof(int));
for(count=0; count<50; count++)
{ //for loop to read the grades till array size
printf("-------------------Enter percentage--------------- Add marks(a) Quit(q) ");
scanf("%c",&choice);
if(choice == 'a')
{ //if user choice is a, then read the grade
printf( "Enter grade:");
scanf("%d", &percentage);
getchar();
percentArray[count] = percentage; //add the grade to array
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
printf("Grades are: ");
for(i=0; i<count; i++)
{
printf("%d ", percentArray[i]); //print grades
}
printf(" ");
free(percentArray);
return 0;
}
Sample Output:
-------------------Enter percentage---------------
Add marks(a)
Quit(q)
a
Enter grade:12
-------------------Enter percentage---------------
Add marks(a)
Quit(q)
a
Enter grade:24
-------------------Enter percentage---------------
Add marks(a)
Quit(q)
a
Enter grade:77
-------------------Enter percentage---------------
Add marks(a)
Quit(q)
q
Grades are: 12 24 7