#include <stdio.h>
#include <stdlib.h>
int main( void ) {
char *ptr1 = "Hello World\n";
char *ptr2;
ptr2 = ptr1 + 6;
ptr2 = "Test!\n";
printf("%s",ptr2);
printf("%s",ptr1);
return EXIT_SUCCESS;
}
Output:
Test!
Hello World
Why didn’t I get Hello Test!?
I thought id would overwrite the World-part from ptr1.
When you assign something to a pointer, such as
ptr1orptr2. you are not changing the value of what is stored there, you are just changing what they point to.When you say:
You are making
ptr2point to the 6th element ofptr1‘s string. Then you say:This means
ptr2is now pointing to a new, different string, elsewhere in memory, which contains"Test!\n". So you have this:Now, when you print them, you get: