Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: pointer to struct in the struct definition

Tags:

c

pointers

struct

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.

like image 410
claf Avatar asked Feb 03 '09 08:02

claf


People also ask

Can you have a pointer to a struct in C?

Similarly, we can have a Pointer to Structures, In which the pointer variable point to the address of the user-defined data types i.e. Structures. Structure in C is a user-defined data type which is used to store heterogeneous data in a contiguous manner.

How do I turn a pointer into a struct?

There are two ways of accessing members of structure using pointer: Using indirection ( * ) operator and dot ( . ) operator. Using arrow ( -> ) operator or membership operator.

How a pointer to a structure is declared in C?

Structure pointer in C is declared using keyword struct followed by structure name to which pointer will point to follower by pointer name. A structure pointer can only hold the address of a variable of the same structure type used in its declaration.

Which pointer is used to point at the instance of a structure?

In the above code s is an instance of struct point and ptr is the struct pointer because it is storing the address of struct point. Below is the program to illustrate the above concepts: C.


1 Answers

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.

like image 79
CB Bailey Avatar answered Sep 17 '22 12:09

CB Bailey