简体   繁体   English

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

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

I have a structure 我有一个结构

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;

I'm passing this structure as an argument to a function and How can I get/access the elements of structure by memory location(in other words i want to treat this structure by memory address) 我正在将此结构作为函数的参数传递,以及如何通过内存位置获取/访问结构的元素(换句话说,我想通过内存地址来处理此结构)

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
}

Is giving me the result 给我结果

203
0x8049780
0x8049aac

But it should give 8048780+4 = 8048784 right.. am I missing something 但是它应该给8048780 + 4 = 8048784对..我错过了什么吗

This works for me: 这对我有用:

 void foo(cfg * ptr)
 {
     printf("%zu\n", sizeof(*ptr));
     printf("%p\n", ptr);
     printf("%p\n", (void *)((char *) ptr + 4));
 }

And then: 接着:

 $ ./a.out 
 203
 0x7fffb6d04ee0
 0x7fffb6d04ee4

When you used (ptr + 4) alone, you essentially got (ptr + 4 * sizeof(cfg)) , because pointer arithmetic works with the size of the pointee, as someone already commented. 当您单独使用(ptr + 4)时,实际上就得到了(ptr + 4 * sizeof(cfg)) ,因为正如有人已经评论过的那样,指针算法与指针对象的大小配合使用。

Also, format specifier %p should be used for addresses. 另外,格式说明符%p应该用于地址。

Try this: 尝试这个:

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
}

If your goal is to access the internal elements of the structure by using index offsets, I recommend implementing a hash table. 如果您的目标是使用索引偏移量访问结构的内部元素,则建议实现一个哈希表。

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

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