C:结构体定义中的结构体指针 [英] C: pointer to struct in the struct definition

查看:43
本文介绍了C:结构体定义中的结构体指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在此结构的定义中获得指向下一个结构的指针:

How can I have a pointer to the next struct in the definition of this struct:

typedef struct A {
  int a;
  int b;
  A*  next;
} A;

这是我第一次写它的方式,但它不起作用.

this is how I first wrote it but it does not work.

推荐答案

您可以在一个语句中先定义 typedef 并转发声明结构体,然后在后续定义中定义结构体.

You can define the typedef and forward declare the struct first in one statement, and then define the struct in a subsequent definition.

typedef struct A A;

struct A
{
    int a;
    int b;
    A* next;
};

正如其他人所提到的,如果没有前向声明,结构名称在结构定义内仍然有效(即您可以使用 struct A),但直到 typedef 之后 typedef 才可用定义是完整的(所以只使用 A 是无效的).这对于只有一个指针成员可能没有太大影响,但如果您有一个包含大量自类型指针的复杂数据结构,则可能不太有用.

As others have mentioned, without the forward declaration the struct name is still valid inside the struct definition (i.e. you can used struct A), but the typedef is not available until after the typedef definition is complete (so using just A wouldn't be valid). This may not matter too much with just one pointer member, but if you have a complex data structure with lots of self-type pointers, may be less wieldy.

这篇关于C:结构体定义中的结构体指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆