memory()函数的C语言输出错误



不明白为什么我从这段代码中得到这个输出。

#include<stdio.h>
#include<string.h>
int main()
{
char str[] = "I live in NY city";
printf("%s%sn","The string in array str[] before invokihg the function memmove(): ",str);
printf("%s%sn","The string in array str[] before invokihg the function memmove(): ",memmove(str,&str[7],10));
return 0;
}

我的输出是:in NY cityNY city
这不应该是:in NY city i live吗??

这是我书中类似的例子,它很有道理。

#include<stdio.h>
#include<string.h>
int main()
{
char x[] = "Home Sweet Home";
printf("%s%sn","The string in array x[] before invoking the function memmove(): ",x);
printf("%s%sn","The string in array x[] before invoking the function memmove(): ",memmove(x,&x[5],10));
return 0;
}   

这里的输出是:Sweet Home Home
根据memmove()函数的定义,这是正确的,也就是说,将指定数量的字节从其第二个参数指向的对象复制到其第一个参数所指向的对象中。(在同一字符串内(这里的object也指一个数据块。

您的期望是错误的。

您定义了一个字符串:

char str[] = "I live in NY city";

然后将10个字节从字符串的末尾移动(复制(到开头:

"I live in NY city";
012345678901234567
/        /
/        /
/        /
/        /
/        /
/        /
"in NY cityNY city";

其他一切都没有触及。

我认为您有一种错误的印象,认为memmove应该以某种方式交换目标和源的非重叠部分。这不是它的工作方式。你可能混淆了你书中的例子,因为"家"这个词出现了两次。将其更改为"Home Sweet Home",这样您就可以看到发生了什么,然后阅读memmove的文档/规范,而不是猜测它的作用。

最新更新