【问题标题】:Access nested struct with offset访问带有偏移量的嵌套结构
【发布时间】:2020-05-10 01:02:50
【问题描述】:

我想使用结构偏移来访问结构的嵌套元素,但以下测试程序没有正确复制字符串。我该如何解决这个 sn-p(它崩溃)。它似乎没有跳转到嵌套结构。

#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;
}

【问题讨论】:

  • 考虑&amp;test.foo 的类型以及指针运算的工作原理。 (或者只打印与printf+%p 相关的各种指针。)另外,什么时候比&amp;test.foo.c 更好?
  • 哦,是的,你是对的。它将多次抵消 foo_t 的大小。我正在尝试缩短我的代码,该代码对字符串列表进行字符串比较并将内容复制到结构中。如果我知道偏移量,我可以将它存储在一个数组中并迭代以缩短我的代码。

标签: c memcpy


【解决方案1】:

您正在偏移 "foo_t" 指针,因此它将等效于 &test.foo[offsetof(foo_t, c)] 因为 "&test.foo" 是 "foo_t*" 的类型...

您需要告诉编译器偏移量以字节为单位,具体如下:

memcpy((char*)(&(test.foo)) + offsetof(foo_t, c), "hello", sizeof("hello"));

因为 offset of 给你以字节为单位的偏移量,你需要使用字节偏移量来计算。因此,如果您需要访问成员“b”,您应该编写如下:

int * ptrB = (int*) ((char*)(&(test.foo)) + offsetof(foo_t, b));
*ptrB = 15;

我们在下面所做的是,我们首先将指针转换为字节,以便编译器将偏移量计算为字节,然后我们可以返回原始指针类型。

【讨论】:

  • 哦,是的,该死的。谢谢
猜你喜欢
  • 2019-06-24
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
相关资源
最近更新 更多