c - 使用 memcpy 和 offsetof 复制结构的一部分
问题描述
offsetof
我想通过组合宏和来复制从某个元素开始的结构的一部分memcpy
,如下所示:
#include <stdio.h>
#include <string.h>
#include <stddef.h>
struct test {
int x, y, z;
};
int main() {
struct test a = { 1, 2, 3 };
struct test b = { 4, 5, 6 };
const size_t yOffset = offsetof(struct test, y);
memcpy(&b + yOffset, &a + yOffset, sizeof(struct test) - yOffset);
printf("%d ", b.x);
printf("%d ", b.y);
printf("%d", b.z);
return 0;
}
我希望这会输出4 2 3
,但它实际上输出4 5 6
就好像没有发生复制一样。我做错了什么?
解决方案
您正在对错误类型的指针进行指针运算,并且正在写入堆栈上的一些随机内存。
由于要计算字节偏移量,因此必须使用指向字符类型的指针。所以例如
memcpy((char *)&b + yOffset,
(const char *)&a + yOffset,
sizeof(struct test) - yOffset);
推荐阅读
- swift - 将数据从 NSViewController 传递到 NSSplitViewController 中的另一个 NSViewController?
- java - 使用函数接口抽象公共代码的问题
- javascript - 如果属性值为 false,则保留扩展样式组件的默认值
- ios - OpentTok (iOS) 如何订阅 hasAudio 流的变化
- c - C、链表中的Segmentation Fault
- android - 有意图地传递原始相机字节数组
- javascript - 为什么我的路线返回 404 错误 Laravel?
- c# - 当实例化的游戏对象被销毁时,它不再产生克隆
- ios - Ios - 按下 UIButton 时更改 UIImageView 的图像
- python - Python 二维数组处理