繁体   English   中英

如何使用指针将结构视为存储位置和访问元素

[英]How to treat a structure as a memory location and access elements separately using pointers

我有一个结构

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)) ,因为正如有人已经评论过的那样,指针算法与指针对象的大小配合使用。

另外,格式说明符%p应该用于地址。

尝试这个:

void foo(cfg *ptr)
{
    printf("%zu\n",sizeof(cfg)); //Gives size of the strcture
    printf("%x\n",ptr); //Gives the starting address of strcure
    printf("%x\n",ptr->role);  //I want to access the 4th element/ memorylocation
}

如果您的目标是使用索引偏移量访问结构的内部元素,则建议实现一个哈希表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM