why this C++ code cannot print the content of the dereference of a pointer
I have not used c++ for a long while so maybe I forget some very simple trick. Here is the code and I tried to print the content of *p and got nothing printed out.
#include <iostream>
using namespace std;
int main() {
char hello[] = "hello";
char *p = hello;
while (*p) {
*p += 1; // increase the character by one
p += 1; // move to the next spot
}
cout << "content of hello is: " << hello << endl;
cout << "content of hello is: " << *p << endl;
return 0;
}
Good thing is I figured out by myself while writing this question. The reason is very simple: p is a pointer type for char, and the p is altered in the while loop. So this will print out i:
cout << "content of hello is: " << *(p - 5) << endl;
Just note it here.
C-strings, which you're dealing with here, are terminated by a null character ('\0'
). That's why looping while *p
is true works. When p
points to a null terminator, dereferencing it gives us 0
, which is false.
Your loop increments p
until it points to the null terminator. That means at the conclusion of the loop, it must be pointing to '\0'
which counts as an empty C-string. Your program then prints that empty string.