Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Pointers Inside Structs | Pointers and Structs
C Structs
course content

Contenido del Curso

C Structs

C Structs

1. Introduction to Structs
2. Pointers and Structs
3. Structs and Memory
4. Advanced Structs Usage
5. Implementing Data Structures

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.

c

main

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 = { .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.

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

Selecciona la respuesta correcta

¿Todo estuvo claro?

Sección 2. Capítulo 3
We're sorry to hear that something went wrong. What happened?
some-alt