简体   繁体   English

C中嵌套结构的指针类型

[英]Pointer type for nested struct in C

Is it possible to create a pointer to the inner struct of a 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;
}

Using a void pointer I could point to it, but I get this error 使用空指针,我可以指向它,但出现此错误

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));
                          ^~

when trying to get the size of the 'third' array. 尝试获取“第三”数组的大小时。 I could also use a pointer to outer_struct but the real example is event more nested and contains long variable names, making it hard to read. 我也可以使用指向external_struct的指针,但真正的示例是事件更嵌套,并且包含长变量名,这使得它很难阅读。 Is it possible to create a pointer to the inner struct directly? 是否可以直接创建指向内部结构的指针?

Using struct inner_struct * p = &foo.inner_struct; 使用struct inner_struct * p = &foo.inner_struct; instead of void yields 而不是无效收益

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));
                          ^~

The type void * is a generic pointer that can point to anything. 类型void *是可以指向任何内容的通用指针。 But the compiler doesn't actually know what it points to, so you have to tell it by using casting. 但是编译器实际上并不知道它指向什么,因此您必须使用强制转换来告诉它。

So for p->third to work, you need to cast the pointer p to the correct pointer type. 因此, p->third起作用,您需要将指针p转换为正确的指针类型。

Unfortunately this is not possible with your current code, as the inner structure is an anonymous structure without a known tag (structure name). 不幸的是,这在您当前的代码中是不可能的,因为内部结构是没有已知标记 (结构名)的匿名结构。 You need to create a structure tag that you can use for the casting. 您需要创建一个可用于铸造的结构标签。 For example 例如

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

Now you can cast the pointer p , like ((struct inner_struct *) p)->third . 现在您可以((struct inner_struct *) p)->third指针p ,例如((struct inner_struct *) p)->third

Or define p to be the correct type immediately: 或立即将p定义为正确的类型:

struct inner_struct *p = &foo.inner_struct;

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

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