I have a small piece of code which does something funny, but I can’t figure out how it does it.
int main(int argc, const char * argv[])
{
char text[] = "object";
for(char *ptr = &text[0]; *ptr != '\0'; ptr+=2)
{
cout << ptr << endl;
ptr--;
}
return 0;
}
What’s happening is that it goes from [1], [2], [3] and so on, to the end of the string every time, printing the content out. I cant understand how it does that, as pointer never gets dereferenced, but right letters seems to get printed. I would assume that instead of the letters of the string, the pointer values would print as weird characters thats all, yet, that’s not what happens.
This is undefined behavior. The first iteration,
ptrpoints to"object". All good, prints that out, but then you doptr--. So now,ptrpoints to memory you no longer own. As long as you don’t dereference it or do pointer arithmetics on it, it’s ok. But you do when you increment it in the loop –ptr+=2.Why it’s behaving like this:
At the first iteration,
ptrpoints to"object", so it prints that.cout::operator << (const char*)prints a null-terminated string. Nocharneeds dereferencing.On the second iteration,
ptris decremented and then increased by2, pointing to"bject". And so on…