There is something that has been bugging me for a while and I need an anwer for it,
char *p = "hello world";
p="wazzup";
p="Hey";
Here I declare an pointer to point to a string (or in other words I made a string by using a pointer)
I have had some strange results with this that i normally wouldnt have gotten if I used an char array string
cout <<p<< endl; //"Hey" Gets printer
cout <<p+8<< endl; // I kept adding numbers till "wazzup" got printed
cout <<p+29<< endl; // No matter how much I increment, I cant print "Hello World"
So my question is:
When I change the value that a char pointer is pointing to. Does it
-
overwrite the original Data like it would do with char array;
-
or it creates a new string right before it in the memory and points to it;
-
or does it add the new string at the begining of the old one(including null);
-
or does it create a new string in a new place in the memory and I was able to print “wazzup” only by chance
It does none of the options above. Changing the value of a pointer merely changes to the address in memory it points to. In each case of the assignments to
p, it is set to point to the first character of a (different) string literal – which is stored in memory.The behaviour of using a pointer that points beyond the end a string literal such as
cout <<p+8<< endlis undefined. This is why using pointers is fraught with danger.
The behaviour you are seeing is implementation dependant: The compiler stores the strings literals adjacent in memory, so running off the end of one runs into another. Your program might equally have crashed when compiled with a different compiler.