我开始学习C的基础知识,但我对这个简单的程序产生了奇怪的结果,因为我很执迷。我想做的是使用memcpy()函数将一个数组的内容复制到另一个数组中。
#include <stdio.h>
#include <string.h>
int main()
{
char source[13] = "Hello, World!";
char destination[13];
memcpy(&destination, &source, 13);
printf("%s\n", destination);
return 0;
}
“奇怪的”输出是:
Hello, World!Hello, World!(
让我想知道为什么会发生这种情况的原因是,如果我以memcpy方式将其从13更改为12,则输出正确,显然没有最后一个字符:
Hello, World
所以,我的问题是:“我缺少什么?我不知道一些理论基础吗?”
#include <stdio.h>
#include <string.h>
int main()
{
char source[14] = "Hello, World!";
char destination[14];
memcpy(&destination, &source, 14);
printf("%s\n", destination);
return 0;
}
char source[13] = "Hello, World!";
不包含字符串,因为它只有13个元素。因此,它没有空间来将使用的字符串文字的结尾零作为初始化程序。
要输出数组,您需要使用另一种格式
printf("%.*s\n", 13, destination);
这里是示范节目
#include <stdio.h>
#include <string.h>
int main()
{
enum { N = 13 };
char source[N] = "Hello, World!";
char destination[N];
memcpy( destination, source, N );
printf( "%.*s\n", N, destination );
return 0;
}
其输出为
Hello, World!
或者,您可以将数组定义为具有14个元素,其中一个元素保留为终止零。
请注意在memcpy
的调用中使用以下参数是正确的>
memcpy( destination, source, 13 );