我有下面的代码。我试图将一个结构复制到一个字符串中。我想了解为什么输出在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)基思·汤普森的建议
下面是生成的警告。
incompatible pointer types passing 'struct a *' to parameter of type 'const char *' [-Wincompatible-pointer-types]2)我稍微修改了代码以使用int数组:
(把这个作为参考。我理解在这种情况下,memcpy在数组的前两个元素中复制struct的变量,因为对struct变量来说,这个大小就足够了。)
#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;
}下面是o:
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]发布于 2014-12-01 19:13:23
但我在结构中没有'\0‘值。
实际上,至少有六个'\0'-s :假设int是32位,98和88的前三个字节都是零。他们会让strncpy停止复制。函数是为固定长度的字符串设计的,因此不应该将其与任意的structs一起使用。另一方面,memcpy会复制所有内容。
这样做的目的:试图通过网络发送一个结构。
如果您希望通过网络发送您的struct,并且希望该数据包是可移植的,则将两个int转换为发送方的网络订单,并在接收方将其转换为硬件顺序。对于32位数字,使用 functions。
发布于 2014-12-01 19:13:09
memcpy复制字节,strcpy复制以nul结尾的字符串(nul是0字节,0x00,'\x00')
memcpy总是复制指定的字节数。当找到nul时strcpy停止复制。
发布于 2014-12-01 19:13:20
但我在结构中没有'\0‘值。
不,你需要。整数值有0位,当字节数据被解释为字符时,可以将其解释为'\0'。因为strncpy“逐字符工作,直到到达终止符”,这会导致它提前停止。
memcpy总是复制指定的字节数,这使得它能够工作。在这种情况下更合适。
https://stackoverflow.com/questions/27235440
复制相似问题