OK. I thought I understood pointers and such but this exercise is revealing that I do not. The task is to read characters into an array created on free store memory (heap), then print them out using the reference and dereference operators.
My code (below) compiles and runs but does not deliver the correct output. The value pointed to is special character like a playing card suit or a brace bracket. The address is the same for all the characters. The variable is not incrementing or it is always pointing to the first element of the array. I need help figuring out what is going on. Here is my code:
#include "../../std_lib_facilities.h"
int main ()
{
char* ch = newchar[10];
char c = ' ';
cout << "Enter characters separated by a space.\nUse the '!' to indicate the end of your entries." << endl;
while (cin >> c) {
if (c == '!') {
break;
} else {
*ch = c;
ch++;
}
}
for (int i = 0; i < 10; i++) {
cout << *ch << " " << &ch << endl;
ch++;
}
delete[] ch;
keep_window_open();
return 0;
}
In your while loop, you are incrementing your pointer, but it is never decremented, meaning that when you go to print out the characters later, you are starting 1 after the end (so you never see anything you input).
Yes. I was incrementing the pointer without ever resetting it back to its beginning. The increment in line 19 starts at an empty address. Another poster advised me to use char *init_ch = ch to set the value of the first element, and then ch = init_ch to reset the pointer to its original value. It works!
@ Disch,
I don't understand what you mean. I have only 1 pointer called 'ch'. What else is there besides the char 'c'?
The same problem you had with printing is also a problem with deleting:
1 2 3 4 5 6 7 8 9 10 11
char* ch = newchar[10]; // let's say, for example, this returns 0x8000000
// so 'ch' points to 0x80000000
// and new allocated memory at 0x80000000
ch++; // now ch == 0x80000001
delete[] ch; // attempts to delete 0x80000001
// but you didn't allocate memory at 0x80000001! You allocated at 0x80000000
// so that's a big problem. Might result in a program crash, or memory corruption, or other
// nasty bugs