[英]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.