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