user3750888 user3750888 - 3 months ago 13
C++ Question

What does "on the Heap" mean?

I have to code the answer to this question for a programming class:


Create an array of 20 test scores between 10 & 90 on the Heap using a Random Number generator to populate the array and for testing your program.


I can do all of that except I don't know what "on the Heap" means. I understand it has something to do with memory, but I'm not sure what it is exactly. I've come up with this solution:

#include "stdafx.h"
#include <iostream>
using namespace std;

void main()
{
int scores[20] = {};
for (int i = 0; i < 20; i++) {
scores[i] = rand() % 80 + 10;
}
for (int i = 0; i < 20; i++) {
cout << scores[i] << " ";
if ((i+1) % 5 == 0) {
cout << "\n";
}
}
}


This section of the class is about pointers, and I didn't really use any pointer variables (like
int *score = scores
), so that makes me second guess myself.

Answer

The heap is the memory used for dynamic allocation of memory by new and delete.

So you should be using:

int *scores = new int[20]

instead of

int scores[20];

And at the end of the program you should release the memory with:

delete[] scores;