C: pointer to struct in the struct definition

余生颓废 提交于 2020-01-08 12:23:25

问题


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.


回答1:


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;
};

Edit: 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.




回答2:


In addition to the first answer, without a typedef and forward declaration, this should be fine too.

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



回答3:


You are missing the struct before the A*

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



回答4:


You can go without forward declaration:

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



回答5:


Please, you're in C, not C++.

If you really must typedef a struct (and most programmers that I work with would not¹), do this:

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

to clearly differentiate between _A (in the struct namespace) and A (in the type namespace).

¹typedef hides the size and storage of the type it points to ― the argument (and I agree) is that in a low-level language like C, trying to hide anything is harmful and counterproductive. Get used to typing struct A whenever you mean struct A.




回答6:


typedef struct {
 values
} NAME;

This is shorter way to typedef a struct i think its the easiest notation, just don't put the name infront but behind.

you can then call it like

NAME n;  

NAME *n; // if you'd like a ptr to it.

Anything wrong with this approach?




回答7:


Use the following preprocessor:

#define structdef(NAME) typedef struct NAME NAME; struct NAME 

Usage:

structdef(node_t)
{
   void* value;
   node_t* next;
};


来源:https://stackoverflow.com/questions/506366/c-pointer-to-struct-in-the-struct-definition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!