簡體   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