这是我几天后在学校进行的测试中可能会出现的问题之一。我无法理解 char* s2 在最后一次 strcpy() 调用后如何从“消息服务”更改为 “ice”。我认为这是指针的某种结果,但这就是我所知道的。
char s1[] = "Short Message Service";
char *s2, *s3;
s2 = strchr(s1, 'M');
s3 = strrchr(s2, 'S');
strncpy(s1 + 1, s2, 1);
strcpy(s1 + 2, s3);
我尝试调试程序并观察变量和指针的变化,但我仍然不明白最后一次调用如何影响 char *s2。
我期望 s2 的值是“Message Service”,但实际输出最终是“ice”。不过,我确实理解 s1 和 s3 如何以及为何变化。
最佳答案
如果我们显示数组,并添加相应的指针,它将看起来像这样:
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+ | 'S' | 'h' | 'o' | 'r' | 't' | ' ' | 'M' | 'e' | 's' | 's' | 'a' | 'g' | 'e' | ' ' | 'S' | 'e' | 'r' | 'v' | 'i' | 'c' | 'e' | '\0' | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+ ^ ^ ^ | | | s1 s2 s3
When you modify the contents of the array, the pointers s2
and s3
themselves doesn't change, they still point to the same locations in the array.
So after
strncpy(s1 + 1, s2, 1);
数组(带有指针)看起来像
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+ | 'S' | 'M' | 'o' | 'r' | 't' | ' ' | 'M' | 'e' | 's' | 's' | 'a' | 'g' | 'e' | ' ' | 'S' | 'e' | 'r' | 'v' | 'i' | 'c' | 'e' | '\0' | +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+ ^ ^ ^ | | | s1 s2 s3
The single character that s2
is pointing to is copied to s1[1]
.
Then with
strcpy(s1 + 2, s3);
数组看起来像
+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+ | 'S' | 'M' | 'S' | 'e' | 'r' | 'v' | 'i' | 'c' | 'e' | '\0' | 'a' | 'g' | 'e' | ' ' | 'S' | 'e' | 'r' | 'v' | 'i' | 'c' | 'e' | '\0' | +-----+-----+-----+-----+-----+-----+-----+-----+-----+------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+ ^ ^ ^ | | | s1 s2 s3
子字符串“Service”
被复制到从s1[2]
开始的字符串部分。
指针s2
仍然指向相同的位置,但是如果我们将s2
视为指向字符串第一个字符的指针,那么它的内容已经改变,因为你已覆盖该内容。
关于c - 最后一次 strcpy() 调用后 char* s2 到底如何以及为何发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56517822/