C++, weird behavior about copying char arrays by using pointers -


i got code 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 code, output p1=hello,world!p2= can understand.

but if uncomment loop, output shows here got confused, why after loop, why shows p1= instead of showing p1=hello,world!, , pointer p2, after assignment in loop, still shows p2=?

but after uncomment p1=str1; p2=str2; line, output p1=hello,world!, p2=hello,world!, why works that?

and what's reason writing line *p2='\0';, doesn't matter line commented out or not, previous outputs don't change.

can tell me how char pointer here working?

the code copying str1 str2.

in c++, '\0' used end string. when try print char pointer (say ptr), compiler prints string starting *ptr (the character pointed pointer). when compiler finds '\0', stops printing.

in beginning, p1 points first char of str1 , p2 points first char of str2. if print them without doing else, compiler print both strings out completely. output p1=hello,world!p2=.

the loop makes p1 , p2 advance through str1 , str2. @ end, p1 points \0 @ end of str1 , p2 points '\0' @ end of str2. if print p1 or p2 directly after loop ends, compiler find '\0' , stop printing. so, output p1=p2=.

uncommenting p1=str1; p2=str2; make both strings point first characters again, printing them cause whole string printed. output p1=hello,world!p2=hello,world! (because str1 got copied str2 in loop).

the *p2 = '\0' ending str2 '\0'. if code works without line, means compiler initialized characters of str2 '\0' automatically. however, compiler isn't guaranteed that, should terminate strings '\0' in programs.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -