在 C 中使用 memcpy 访问结构成员

Accessing Struct members using memcpy in C

我有这样的结构:

struct x{
int a;
int b;
int c;
}

我有一个这样的数组:

unsigned char bytes[8];
bytes[0] = 1
bytes[1] = 128
bytes[2] = 0
bytes[3] = 0
bytes[4] = 255
bytes[5] = 255
bytes[6] = 0
bytes[7] = 0

我想复制结构元素"a"中的字节[0]到字节[3],结构元素"b"中的字节[4]到字节[6]和结构元素"b"中的字节[7]结构元素 "c"。我必须使用 memcpy。 我怎样才能做到这一点?请帮忙。

我的尝试:

struct x test;
memcpy( &test.a, bytes, 4);
memcpy( &test.b, bytes + 4, 3);
memcpy( &test.c, bytes + 7, 1);

但是每次我 运行 它都显示不同的结果。

在您的代码中您没有初始化 test。所以最终发生的是:

  • 字段最初有未定义的("garbage")数据
  • 您只部分写入字段

例如,当您执行 memcpy( &test.b, bytes + 4, 3); 如果您有 sizeof(int) == 4(可能),您最终只写了 3 个字节,因此 留下一个未定义的字节

尝试一些简单的事情,比如初始化对象:

struct x test = {0};