c - 用于结构复制的 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,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 会在数组的前两个元素中复制 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\p:

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]

最佳答案

but I don't have '\0' value in the struct.

实际上,那里至少有六个 '\0':假设 int 是 32 位,两个 的高三个字节9888 都是零。他们会让 strncpy 停止复制。该函数专为固定长度的字符串而设计,因此不应将其与任意 struct 一起使用。另一方面,memcpy 将复制所有内容。

Purpose of doing this: trying to send a struct over network.

如果您想通过网络发送您的struct,并且您希望数据包是可移植的,请在发送方将两个int 转换为网络顺序, 并返回到接收方的硬件订单。对于 32 位数字,使用 htonl and ntohl functions .

关于c - 用于结构复制的 memcpy 和 strncpy 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27235440/

相关文章:

c - 避免使用相似的结构重复代码 C

c++ - 复制类的一部分

c - 释放变量 malloc 并在 c 中的函数中返回?

c - 如何从磁盘来回保存和加载一个巨大的哈希表?

c# - Unity Array of Struct : When setting a variable of one of the array subscripts, 它为所有这些设置它

c - 在 C 错误消息中返回结构体数据类型

c - 来自未初始化变量的 memcpy 是未定义的行为吗?

c++ - 我可以调用 memcpy() 和 memmove() 并将 "number of bytes"设置为零吗?

c# - 在 C# 中模拟 C 数据类型

c - 如何从/dev/xxxx读取数据?