Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Pointers Inside Structs | Section
C Structs

bookPointers 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
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:

struct Node {
    int data;
    struct Node next; // error: `Node` structure contains itself
};

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:

struct Node {
    int data;
    struct Node *next; // pointer to the `Node` structure
};

This code works because the compiler knows the exact size of a pointer — usually 4 or 8 bytes, depending on the system.
It doesn't try to calculate the size of the entire nested structure; it simply stores a reference (address) to it.

Let's see how this works in practice.

main.c

main.c

copy
1234567891011121314151617181920212223242526
#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 = { "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
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.

question mark

Why can't we create a structure that contains itself?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  7

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  7
some-alt