tags:

views:

8515

answers:

5

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.

+15  A: 

You can define the typedef and forward declare the struct first in one statment, 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 declaratation 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.

Charles Bailey
This is the "canonical" way of doing this.
unwind
unwind: many coding style conventions for C vehemently oppose typedefing structs. I wouldn't say it's canonical at all.
Chris Young
If I could vote up comments, Chris Young would get a +1. There is a huge difference between native types and aggregate structures. **Don't** hide it behind a typedef.
ephemient
+25  A: 

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; 
};
Chris Young
+8  A: 

You can go without forward declaration:

struct A {
    int a;
    int b;
    struct A *next;
};
qrdl
+7  A: 

You are missing the struct before the A*

  typedef struct A {
    int a;
    int b;
    struct A* next;
  } A;
Miles D
+2  A: 

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.

ephemient
How does "struct A" tell me anything about its size?
quant_dev
It tells you that it's an aggregate structure, and thus many things like passing it as arguments, returning it, comparisons, and `a = b` are inefficient or will not work.
ephemient
_A is a reserved name. A_ would be fine.
MSalters
Nitpick: _A is a bad name: leading underscores belong to the compiler. [edit] Damn, I think I just echoed MSalters.
Bernd Jendrissek