c - 访问带有偏移量的嵌套结构
问题描述
我想使用结构偏移来访问结构的嵌套元素,但以下测试程序没有正确复制字符串。我该如何修复这个片段(它崩溃了)。似乎它没有跳转到嵌套结构。
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
typedef struct {
char a;
int b;
char c[10];
char d[10];
}foo_t;
typedef struct {
foo_t foo;
}super_foo_t;
super_foo_t test;
int main() {
memcpy(&(test.foo) + offsetof(foo_t, c), "hello", sizeof("hello"));
printf("c should be hello:%s\n", test.foo.c);
return 0;
}
解决方案
您正在偏移“foo_t”指针,因此它将等效于 &test.foo[offsetof(foo_t, c)] 因为“&test.foo”是“foo_t*”的类型...
您需要告诉编译器偏移量以字节为单位,具体如下所示:
memcpy((char*)(&(test.foo)) + offsetof(foo_t, c), "hello", sizeof("hello"));
因为偏移量为您提供字节偏移量,您需要使用字节偏移量进行计算。因此,如果您需要访问成员“b”,您应该编写如下:
int * ptrB = (int*) ((char*)(&(test.foo)) + offsetof(foo_t, b));
*ptrB = 15;
我们在下面所做的是我们首先将指针转换为字节,以便编译器将偏移量计算为字节,然后我们可以返回原始指针类型。
推荐阅读
- javascript - 是否可以在不重新加载页面的情况下修改 url?
- alias - 领事别名 (CNAME) 取消注册
- simplemodal - 多模式使用 - 错误
- c# - 检查 Null 的更好方法
- php - 未提交带有 Material Bootstrap Select Picker 的 Symfony 4
- sql - 如何在没有联合的情况下使用sql递归?
- ios - 无法更新/修改 SwiftUI 视图的 @state var
- regex - 具有前瞻性的 AWS WAF 正则表达式问题
- javascript - TypeError this is undefined whyle using primereact
- ionic-framework - 如何将 Ionic Splash Screen Spinner 位置更改为底部?