簡體   English   中英

C中嵌套結構的指針類型

[英]Pointer type for nested struct in C

是否可以在C中創建指向嵌套結構的內部結構的指針?

#include <stdio.h>
#include <stdint.h>

typedef struct
{
    uint8_t first;
    struct
    {
        uint8_t second;
        uint8_t third[8];
    } inner_struct;
} outer_struct;

int main()
{
    outer_struct foo;
    void * p = &foo.inner_struct;
    printf("%d", sizeof(p->third));
    return 0;
}

使用空指針,我可以指向它,但出現此錯誤

main.c: In function 'main':
main.c:26:26: error: request for member 'third' in something not a structure or union
     printf("%d", sizeof(p->third));
                          ^~

嘗試獲取“第三”數組的大小時。 我也可以使用指向external_struct的指針,但真正的示例是事件更嵌套,並且包含長變量名,這使得它很難閱讀。 是否可以直接創建指向內部結構的指針?

使用struct inner_struct * p = &foo.inner_struct; 而不是無效收益

main.c: In function 'main':
main.c:25:31: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
     struct inner_struct * p = &foo.inner_struct;
                               ^
main.c:26:26: error: dereferencing pointer to incomplete type 'struct inner_struct'
     printf("%d", sizeof(p->inner_struct.third));
                          ^~

類型void *是可以指向任何內容的通用指針。 但是編譯器實際上並不知道它指向什么,因此您必須使用強制轉換來告訴它。

因此, p->third起作用,您需要將指針p轉換為正確的指針類型。

不幸的是,這在您當前的代碼中是不可能的,因為內部結構是沒有已知標記 (結構名)的匿名結構。 您需要創建一個可用於鑄造的結構標簽。 例如

typedef struct
{
    uint8_t first;
    struct inner_struct
    {
        uint8_t second;
        uint8_t third[8];
    } inner_struct;
} outer_struct;

現在您可以((struct inner_struct *) p)->third指針p ,例如((struct inner_struct *) p)->third

或立即將p定義為正確的類型:

struct inner_struct *p = &foo.inner_struct;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM