C 使用偏移量访问嵌套结构
我想使用结构偏移来访问结构的嵌套元素,但是下面的测试程序没有正确地复制字符串。如何修复此代码段(它崩溃)。它似乎没有跳转到嵌套结构C 使用偏移量访问嵌套结构,c,memcpy,C,Memcpy,我想使用结构偏移来访问结构的嵌套元素,但是下面的测试程序没有正确地复制字符串。如何修复此代码段(它崩溃)。它似乎没有跳转到嵌套结构 #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;
#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;
}
#包括
#包括
#包括
#包括
类型定义结构{
字符a;
int b;
charc[10];
chard[10];
}富特;
类型定义结构{
福特福;
}超级富特;
超级食物测试;
int main(){
memcpy(&(test.foo)+offsetof(foo_t,c),“hello”,sizeof(“hello”);
printf(“c应该是hello:%s\n”,test.foo.c);
返回0;
}
您正在偏移“foo\u t”指针,因此它将等效于&test.foo[offsetof(foo\u t,c)],因为“&test.foo”是“foo\u t*”的类型
您需要告诉编译器偏移量以字节为单位,具体如下所示:
memcpy((char*)(&(test.foo)) + offsetof(foo_t, c), "hello", sizeof("hello"));
int * ptrB = (int*) ((char*)(&(test.foo)) + offsetof(foo_t, b));
*ptrB = 15;
因为的偏移量以字节为单位提供偏移量,您需要使用字节偏移量进行计算。因此,如果您需要访问成员“b”,您应该编写如下内容:
memcpy((char*)(&(test.foo)) + offsetof(foo_t, c), "hello", sizeof("hello"));
int * ptrB = (int*) ((char*)(&(test.foo)) + offsetof(foo_t, b));
*ptrB = 15;
下面我们要做的是,我们首先将指针转换为字节,以便编译器将偏移量计算为字节,然后我们可以返回到原始指针类型。考虑
&test.foo的类型以及指针算法的工作方式。(或者只打印与printf
+%p
有关的各种指针)还有,这什么时候比&test.foo.c
好?是的,你是对的。它会将食物的大小抵消很多倍。我试图缩短我的代码,它对字符串列表进行字符串比较,并将内容复制到结构中。如果我知道偏移量,我可以将它存储在数组中,然后迭代以缩短代码。哦,是的,该死。谢谢