考虑这段代码。
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
}
有 2 个字符串s和t. 首先我设置s为"foo",然后t指向s。当我打印字符串时,我得到foo foo.
然后,复制"bar"到s并再次打印,我得到bar bar.
为什么t在这种情况下价值会发生变化?(我复制"bar"到s为什么t会改变)。
现在,当我更改strcpy(s, "bar")为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
}
这段代码给了我foo foo和bar foo.
为什么在这种情况下没有改变?