Course Content
C Structs
C Structs
Pointers Inside Structs
Essential data structures such as stacks, linked lists, and trees can contain references to other objects of the same type to create connections or relationships between elements. Data structures will be covered later in this course.
Note
Elements of such data structures are usually called nodes.
If you try to create a structure containing a field of the same type as the structure itself, you will receive an error:
In this case, an infinite recursion occurs when determining the size of such a structure.
This idea can be implemented using a pointer to a structure:
Note
This works because the compiler knows how much memory needs to be allocated for a variable of type pointer.
main
#include <stdio.h> struct Node { char name[20]; struct Node* next; }; int main() { struct Node Kate = {"Kate" }; struct Node Tom = { "Tom" }; struct Node Bob = { "Bob" }; Kate.next = &Tom; // Kate --> Tom Tom.next = &Bob; // Tom --> Bob // set a pointer to the first structure in the chain struct Node* pointer = &Kate; while (pointer != NULL) { printf("Address: %p | Name: %s-> | Next address: %p\n", pointer, pointer->name, pointer->next); pointer = pointer->next; // go to the next object } return 0; }
struct Node kate = { .Name = "Kate" };
- the next
field was not initialized explicitly in the struct initializer, it will be automatically initialized to a null pointer (NULL), since this is the standard value for pointers when they do not point to any object.
while (pointer != NULL)
- the loop will run until the pointer points to NULL address .
Note
In programming languages such as C and C++, a pointer that is NULL usually means the end of a list (or other data structure). Therefore, this loop will execute until pointer is NULL, which can be interpreted as reaching the end of the list or data structure.
Thanks for your feedback!