I’ve been staring at this for a while now and I’m confused about what is happening in regards to my for loop.
To start, I am having the user enter a phrase which is read using cin.getline()
const int STRING_MAX = 1001;
char* inputString = nullptr;
inputString = new char[STRING_MAX];
cin.getline(inputString, STRING_MAX, '\n');
In case anyone is wondering.. I’m not filling up the buffer (which shouldn’t matter anyway). I’m only entering about 25 characters.
Next inputString is passed by value to the Palindrome class member function
word(char* source)
This is all I’m currently trying to do in the function:
bool Palindrome::word(char* source) {
for (char* iterator = source; iterator != '\0'; iterator++)
cout << *iterator << endl;
}
I’m actually doing more, but at the moment, I reduced the code to what you see above, and for some reason, which I do not understand, the loop runs past the bounds of the char* array
Can someone help me to understand what is happening here?
By the way, I am well aware of the string class in C++, however, for this assignment (the instructor wants us to use pointers and the new and delete operators).
iterator != '\0'This tests whetheriteratoris a null pointer. This will never be the case and it is not what you really want.Your code is incorrect but just happens to be valid code because
'\0'is a lexical representation of the integer value zero, and is thus it happens to be a null pointer constant.To test whether
iteratorpoints to a null terminator, you need to use*iterator != '\0'(or just test*iterator, since an integer value of zero evaluates to false).