结构复制的memcpy和strncpy的区别

结构复制的memcpy和strncpy的区别,c,struct,memcpy,strncpy,C,Struct,Memcpy,Strncpy,我有下面的代码。我正在尝试将结构复制到字符串。我想了解为什么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,siz

我有下面的代码。我正在尝试将结构复制到字符串。我想了解为什么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;
}
我知道strncpy将一直复制到它达到'\0'(或大小限制),但我在结构中没有'\0'值。有人能帮我理解这一点吗。 执行此操作的目的:尝试通过网络发送结构。虽然我计划实现序列化,但我想了解其行为

编辑: 1) 基思·汤普森建议

下面是生成的警告

incompatible pointer types passing 'struct a *' to parameter of type 'const char *' [-Wincompatible-pointer-types]
2) 我稍微修改了代码以使用int数组:

(作为参考,我知道在这种情况下,memcpy会将struct变量复制到数组的前两个元素中,因为struct变量的大小足够了。)

以下是生成的警告:

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]

memcpy复制字节,strcpy复制nul终止的字符串(nul是0字节,0x00,“\x00”)

memcpy始终复制指定数量的字节。strcpy在找到nul时停止复制

但是我在结构中没有'\0'值

是的,你知道。整数值有0位,当字节数据被解释为字符时,可以将其解释为
'\0'
。由于
strncpy
的工作方式是“一个字符接一个字符,直到到达终止符”,因此它会提前停止

memcpy
总是复制指定的字节数,这使它能够工作。在这种情况下更合适

但是我在结构中没有'\0'值

实际上,您至少有六个
'\0'
-s:假设
int
是32位,那么
98
88
的上三个字节都是零。他们会让strncpy停止复制。该函数是为固定长度字符串设计的,因此不应将其用于任意
struct
s<另一方面,code>memcpy将复制所有内容

执行此操作的目的:尝试通过网络发送结构


如果您希望通过网络发送
结构
,并且希望数据包是可移植的,请在发送方将
int
s转换为网络顺序,在接收方将其转换为硬件顺序。对于32位数字,请使用。

您的结构不是字符串<代码>strncpy对字符串进行操作。这个调用甚至不应该编译;您至少应该得到一个警告,将
struct a*
参数传递给
strncpy
,它需要一个
char*
。即使对于字符串,
strncpy
通常也应该避免使用。它确实抛出了警告。请更新您的问题以显示确切的警告;这是非常重要的信息。谢谢@KeithThompson添加了警告。添加了另一个示例牙床,遗漏了“\0”等于0。strcpy将停止在0。谢谢,遗漏了“\0”等于0
#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]