Reputation: 443
typedef struct node
{
int n;
struct node* next;
}
node;
In the above code there is struct node* next
inside the struct node
. I don't understand the meaning of it.
Upvotes: 2
Views: 307
Reputation: 6609
Answering the title: In C
, all non-standard types need to be prefaced with the struct
keyword:
#include <stdint.h>
typedef uint8_t u8;
typedef uint32_t u32;
struct memory_arena {
size_t size;
u8 *base;
size_t used;
u32 _savePointCount;
size_t _savePoints[8];
};
struct application_state {
#if 1
struct memory_arena globalArena; //<---
#else
memory_arena globalArena; //Valid C++
#endif
};
If it were in C-style C++, you might find this mixed and matched because it's not required.
Upvotes: 0
Reputation: 5457
In the code there is
struct node* next
inside thestruct node
. I don't understand the meaning of it.
Explanation :
A node is a general term used to refer a self referential structure.(click on link to know more)
and going by definition,
A self referential structure is a typical structure whose definition has one or more of its member as a pointer to its own type.
Here in your code next
is such a member of the structure struct node
which is a pointer to it's own type therefore you see it as a pointer to itself in this manner inside of struct :
struct node* next;
That's the reason why struct keyword is used inside of struct
Purpose of using self referential structures :
self referential structures are very much helpful in building data structures such a linked lists... and in fact the variable next
is the very member which is useful in making links between nodes in a linked list :)
Upvotes: 5
Reputation: 260
In simple words, it means that next would also be of the same structure as that of node. So next will also have a field int n and another next.. Also this is dynamic so you don't have to allocate any memory before hand.. you can keep on adding as many node as you want ( you still have to assign memory to each node though -- search for how to use malloc to allocate memory to struct node ) And as it is of pointer type ( struct node* next ) it means you can store the address of your next node in to it and link nodes.. See the linked list implementation for better understanding.. I hope it helps :)
Upvotes: 0
Reputation: 17031
struct node*
(note the *
) is a pointer (*
) to a struct node
. That means that one node can connect to another, via the pointer, without including the other.
This is referred to as a "linked list" structure. I found a Stanford University tutorial that looks like it covers the subject fairly thoroughly.
Upvotes: 0