1

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).

  • 1
    Weird code but one excellently phrased question, +1. – Konrad Rudolph Dec 03 '11 at 12:51
  • the test expression in the `for` loop should be written as either `!iterator` or (more completely) as `iterator != NULL`. (`'\0'` is a NUL byte, not a NULL pointer, though "the usual conversions" will allow it to work regardless of how odd it looks) – Greg A. Woods Nov 18 '12 at 02:18

1 Answers1

3

iterator != '\0' This tests whether iterator is 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 iterator points to a null terminator, you need to use *iterator != '\0' (or just test *iterator, since an integer value of zero evaluates to false).

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • OMG. Now I feel like a retard. I don't know how I overlooked that. I must be getting tired. Thank you! –  Dec 03 '11 at 07:34