Can someone explain the output of the following code
char* a[] = {"ABC123", "DEF456", "GHI789"};
char **p = a;
cout<<++*p<<std::endl;
cout<<*p++<<std::endl;
cout<<++*p<<std::endl;
Output:
BC123
BC123
EF456
What is confusing to me is the different behavior of ++*p and *p++. I was expecting the output to be:
ABC123
DEF456
GHI789
On line 1 first
*pwill be pointing to the element in the array"ABC123"and the++moves one forward and so ‘BC123’ is printed.On line 2
*pis still pointing toBC123so this is printed and then once printed the++is carried out. This moves the pointer to the 2nd element in the arrayOn line 3 it is the same as line 1. You have taken the contents of
p(Now the 2nd element in the array) and moved one character in that string, thus printingEF456(Also have a look at here Pointer arithmetic on string type arrays, how does C++ handle this? as I think it might be useful to get an understanding of what is happening)
To print what you expected the following would work:
Or
Or various other ways (taking into account precedence as others have said)