Consider this code.
int main()
{
char *s, *t;
s = malloc(4 * sizeof(char));
strcpy(s, "foo");
t = s;
printf("%s %s\n", s, t); // Output --> foo foo
strcpy(s, "bar"); // s = "bar"
printf("%s %s\n", s, t); // Output --> bar bar
}
There are 2 strings s and t. First I set s to "foo" and then make t point to s. When I print the strings, I get foo foo.
Then, copy "bar" tos and print again, I get bar bar.
Why does value of t changes in this case? (I copied "bar" to s why did t change).
Now when I change strcpy(s, "bar") to s = "bar" -
int main()
{
char *s, *t;
s = malloc(4 * sizeof(char));
strcpy(s, "foo");
t = s;
printf("%s %s\n", s, t); // Output --> foo foo
s = "bar"
printf("%s %s\n", s, t); // Output --> bar foo
}
This code gives me foo foo and bar foo.
Why didn't it change in this case?