When compiling this program I receive an output that I would've never expected. When I reviewed this program I expected the outcome of pointer to be still "Hello, world!" because to my knowledge pointer was never affected by pointer2. Yet, my output shows that when pointer is printed it contains pointer2's string "y you guys!". How is this so?? Thanks!!
#include <stdio.h>
#include <string.h>
int main() {
char str_a[20];
char *pointer;
char *pointer2;
strcpy(str_a, "Hello, world!\n");
pointer = str_a;
printf(pointer);
pointer2 = pointer + 2;
printf(pointer2);
strcpy(pointer2, "y you guys!\n");
printf(pointer);
}
Output
Hello, world!
llo, world!
Hey you guys!
pointeris pointing to the base address ofstr_aand pointer2 is pointing 2 bytes ahead of the base address ofstr_a. So, you are affectingstr_adata each time you're accessing any of the pointers. - pah