Iterating over a char array using pointers

Hi,

I am reading the Stroustrup book. There is a example to find the length of a string held in a char array.

1
2
3
4
5
6
7
8
9
10
11
12
13
int length_of_charachter_string_2(char* p)
{
 
 
      int i = 0;
      while(*p++) {
            
            i++;
 
      }

      return i;
}


I am trying to understand this. I understand the pointer is incremented and then dereferenced, but I am not sure why incrementing a pointer doesnt just run off into memory. Whats the end condition as it dereferences? The Null character? What if a terminating null character isn't present?

Also, when you cout << p, you get the text shrinking:

Fred
red
ed
d


How does this work? How does incrementing the pointer generate a shorter string/array of characters?

Regards

i

What the statement while( *p++ ) means is that first, whatever p is pointing to is dereferenced. If this value is 0 (NULL) the while loop is exited. If it isn't NULL the address of p is incremented by the size of a character and now points to the next contiguous memory location.

You are correct that the NULL character is the condition that terminates the loop, as I said above.

Your last question should be obvious now. Each time that p is incremented, it is pointing at the next character in the string.
Hi,

Thanks. So if this wasn't a null terminated char* array i.e. {'a','b','c'}, is this dangerous? i.e. you would walk off then end of the array?

Also

1
2
3

cout << p << endl;


The reason this gives me for "Fred"

red
ed
d

I am assuming is a consequence of how cout handles a char*, i.e. it just prints the string until a NULL is encountered. Again, what if there is no null?

Thanks for your patience!

Regards

i



Last edited on
indy2005 wrote:
So if this wasn't a null terminated char* array i.e. {'a','b','c'}, is this dangerous?
i.e. you would walk off then end of the array?

Yes. Yes.
Last edited on
Thanks
Topic archived. No new replies allowed.