我有以下代码。我试图将一个结构体复制到一个字符串中。我想知道为什么使用strncpy和memcpy输出结果不同。
#include <stdio.h>
#include<string.h>
struct a{
int len;
int type;
};
int main(){
struct a aa={98,88};
char str[10]="";
char str2[10]="";
strncpy(str,&aa,sizeof(struct a));
memcpy(str2,&aa,sizeof(struct a));
for(int i=0;i<10;i++)printf("%2d",str[i]);
printf("\n");
for(int i=0;i<10;i++)printf("%2d",str2[i]);
return 0;
}
以下是输出结果:
98 0 0 0 0 0 0 0 0 0
98 0 0 088 0 0 0 0 0
我理解strncpy会复制直到遇到'\0'(或大小限制),但是在结构体中我没有'\0'值。请有人帮我理解一下。
这样做的目的:尝试通过网络发送一个结构体。虽然我计划实现序列化,但我想了解其行为。
编辑: 1)由Keith Thompson建议
下面是生成的警告。
incompatible pointer types passing 'struct a *' to parameter of type 'const char *' [-Wincompatible-pointer-types]
2) 我稍微修改了代码,使用了int数组:
(仅供参考。我理解在这种情况下,由于数组大小足够存储结构体变量的前两个元素,memcpy会将结构体变量的变量复制到数组中的前两个元素中。)
#include <stdio.h>
#include<string.h>
struct a{
int len;
int type;
};
int main(){
struct a aa={98,88};
int str[10]={0};
int str2[10]={0};
strncpy(str,&aa,sizeof(struct a));
memcpy(str2,&aa,sizeof(struct a));
for(int i=0;i<10;i++)printf("%2d",str[i]);
printf("\n");
for(int i=0;i<10;i++)printf("%2d",str2[i]);
return 0;
}
以下是问题:
98 0 0 0 0 0 0 0 0 0
9888 0 0 0 0 0 0 0 0
以下是生成的警告:
incompatible pointer types passing 'int [10]' to parameter of type 'char *' [-Wincompatible-pointer-types]
incompatible pointer types passing 'struct a *' to parameter of type 'const char *' [-Wincompatible-pointer-types]
strncpy
是用于操作字符串的。那个调用甚至不应该编译通过;你至少应该得到一个警告,因为你传递了一个struct a*
参数给strncpy
,而它期望的是一个char*
。即使对于字符串,通常也应该避免使用strncpy
;在这里看看我对此的抱怨。 - Keith Thompson