2

I don't know why this code gives the result it does. I thought the pointer p should be the address of str and the output should always be the address in the while loop. Why is the result is the real value of str like that?

char str[] = "we are poor students";//这是一个字符串
cout<<str<<endl;
char *p = str;
while (*p != '\0')
{
    cout << p<<endl;
    p++;
}
return 0;

This is the result it gives:

we are poor students
we are poor students
e are poor students
 are poor students
are poor students
re poor students
e poor students
 poor students
poor students
oor students
or students
r students
 students
students
tudents
udents
dents
ents
nts
ts
s
Miles Budnek
  • 28,216
  • 2
  • 35
  • 52

1 Answers1

9

There is a special overload for const char* to display c-string content, to print the address, cast it to void*:

cout << static_cast<void*>(p) << endl;
Jarod42
  • 203,559
  • 14
  • 181
  • 302