我有一个结构
typedef struct
{
unsigned char status;
unsigned char group_id;
unsigned char acc_trip_level;
unsigned char role[50];
unsigned char standard_panic_header[50];
unsigned char high_threat_message[50];
unsigned char high_threat_header[50];
}cfg;
cfg test_val;
我将此结构作为参数传递给函数以及如何通过内存位置获取/访问结构的元素(换句话说,我想通过内存地址处理此结构)
void foo(cfg *ptr)
{
printf("%zu\n", sizeof(*ptr)); //Gives size of the strcture
printf("%p\n", (void*)ptr); //Gives the starting address of strcure
printf("%p\n", (void*)(ptr+4)); //I want to access the 4th element/ memorylocation
}
正在给我结果
203
0x8049780
0x8049aac
但它应该给出 8048780+4 = 8048784 是对的..我是不是漏掉了什么
最佳答案
这对我有用:
void foo(cfg * ptr)
{
printf("%zu\n", sizeof(*ptr));
printf("%p\n", ptr);
printf("%p\n", (void *)((char *) ptr + 4));
}
然后:
$ ./a.out
203
0x7fffb6d04ee0
0x7fffb6d04ee4
当你单独使用 (ptr + 4)
时,你实际上得到了 (ptr + 4 * sizeof(cfg))
,因为指针运算与pointee,正如有人已经评论过的那样。
此外,地址应使用格式说明符 %p
。
关于c - 如何将结构视为内存位置并使用指针分别访问元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32076373/