I got this code from a textbook:
#include <iostream>
using namespace std;
int main(){
char str1[]="hello,world!", str2[20], *p1, *p2;
p1=str1; p2=str2;
/*
for(;*p1!='\0';p1++,p2++){
cout<<"p1="<<*p1<<endl;
*p2=*p1;cout<<"p2="<<*p2<<endl;
}
*p2='\0';
p1=str1; p2=str2;
*/
cout<<"p1="<<p1<<endl;
cout<< "p2="<<p2<<endl;
return 0;
}
I ran this code, it will output p1=hello,world!p2=
which I can understand.
But if I uncomment the for loop, the output shows here I got confused, why after the for loop, why it shows p1=
instead of showing p1=hello,world!
, and for pointer p2
, even after the assignment in the for loop, it still shows p2=
?
But after I uncomment p1=str1; p2=str2;
this line, the output is p1=hello,world!, p2=hello,world!
, why it works like that?
And what's the reason for writing this line *p2='\0';
, it doesn't matter that this line is commented out or not, the previous outputs don't change.
can anyone tell me how the char pointer here is working?