请考虑此代码。了解字符串和数组
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
。
为什么在这种情况下没有改变?
**版主说明**:玩的很好。保留主题的意见(意思是他们应该要求澄清)。如果你想打开关于这个问题的优点的讨论,去[这里](http://meta.stackoverflow.com)。 –
我已经删除了你的问题的第二部分,如果你仍然想问它,请另写一篇文章。你应该每个帖子只问一个问题。 – sashoalm