代码正在运行,它剪切了第一个单词并将其放在最后的文本中。我不明白代码中的一行,假设我的字符串是“hello world”。
当我使用代码“*p++ = '\0';”时
在此行之前:p: "world"
s: "hello world"
此行之后:p: "world"
s: "hello"
为什么会改变?并删除“世界”这个词?
完整代码:
void func(char *s)
{
char * p = strchr(s, ' ');
char * t = (char*)malloc(strlen(s) + 1);
if (!t)
{
printf("Memory allocated failed");
exit(1);
}
*p++ = '\0';
strcat(strcat(strcpy(t, p), " "), s);
strcpy(s, t);
free(t);
}
最佳答案
在分配给*p
之前,您有以下内容:
+---+---+---+---+---+---+---+---+---+---+---+---+
s: |'H'|'e'|'l'|'l'|'o'|' '|'W'|'o'|'r'|'l'|'d'| 0 |
+---+---+---+---+---+---+---+---+---+---+---+---+
^
+---+ |
p: | | ----------------+
+---+
执行*p++ = '\0';
后,您有
+---+---+---+---+---+---+---+---+---+---+---+---+
s: |'H'|'e'|'l'|'l'|'o'| 0 |'W'|'o'|'r'|'l'|'d'| 0 |
+---+---+---+---+---+---+---+---+---+---+---+---+
^
+---+ |
p: | | --------------------+
+---+
IOW,您已将 s
中的空格替换为字符串终止符,这就是为什么您仅在以下情况下看到“Hello”
你打印s
。
关于C 指针和内存 - 理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46666094/