An exercise is to write a program that shows how memory is allocated to stack variables compared to heap variables. I ran the following code.
#include "../../std_lib_facilities.h"
int main ()
{
char c = ' ';
char ch0[10];
char *ch = new char[10];
char *init_ch = ch;
cout << "Enter characters separated by a space.\nUse the '!' to indicate the end of your entries." << endl;
int i = 0;
while (cin >> c) {
if (c == '!') {
break;
} else {
*ch = c;
ch0[i] = c;
ch++;
i++;
}
}
ch = init_ch;
for (int i = 0; i < 10; i++) {
cout << *ch << " " << reinterpret_cast<void*>(ch) << endl;
cout << ch0[i] << " " << reinterpret_cast<void*>(&ch0[i]) << endl;
cout << endl;
ch++;
}
ch = init_ch;
delete[] ch;
keep_window_open();
return 0;
}
The output I get is an address of 00345A48 for the first element of the ch (heap) array, and an address of 0012FF48 for the first element of the ch0 (stack) array. The addresses of the other elements increase by 1 unit in both arrays.
The illustration in my book of the memory layout shows stack memory 'below' heap memory. I am guessing that means stack memory addresses will have smaller numbers than heap memory addresses, as my output shows.
Is that supposed to happen?
Thanks in advance for explanations.