Understanding Pointers & Indirection
Pointers are a fundamental concept in C, representing the memory location of other variables. This section provides an interactive look at how they, and pointers to pointers, work.
Interactive Pointer Diagram
Click on the variables or pointers in the diagram below to see their relationships, values, and memory addresses.
#include <stdio.h>
void main() {
int a = 10;
int *ptr1;
int **ptr2;
ptr1 = &a;
ptr2 = &ptr1;
printf("a = %d\n", a);
printf("*ptr1 = %d\n", *ptr1);
printf("**ptr2 = %d\n", **ptr2);
printf("Address of a = %p\n", &a);
printf("Value in ptr1 = %p\n", ptr1);
printf("Address of ptr1 = %p\n", &ptr1);
printf("Value in ptr2 = %p\n", ptr2);
}
Self-Referential Structures
These are the building blocks for dynamic data structures like linked lists. A self-referential structure contains a pointer to another structure of the same type, allowing them to be chained together.
Visualizing a Linked Node
The diagram shows two `node` structures linked together. The `next` pointer of the first node holds the memory address of the second, forming a chain. Hover over the `next` pointer to see the connection.
// The definition for a node
struct node {
int value;
struct node *next;
};
// Creating two nodes
struct node *node1, *node2;
// Allocating memory (more on this later)
node1 = malloc(sizeof(struct node));
node2 = malloc(sizeof(struct node));
// Assigning values
node1->value = 10;
node2->value = 20;
// Linking the nodes
node1->next = node2;
node2->next = NULL;
Dynamic Memory Management Playground
Unlike static memory which is fixed at compile-time, dynamic memory can be allocated and deallocated at runtime. This provides flexibility but requires careful management. Use the controls below to see how C's memory functions work on a visual 'heap'.
Memory Controls
Visual Memory Heap
The heap is empty. Use controls to allocate memory.
Code Executed:
Dynamically Allocated Arrays
Dynamic memory allocation allows us to create arrays whose size is determined at runtime. This is especially powerful for handling data of unknown size, including multi-dimensional arrays.
1D Dynamic Array
A 1D dynamic array is a contiguous block of memory, similar to a static array but with a size set at runtime.
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *a;
printf("Enter number of elements: ");
scanf("%d", &n);
// Allocate memory for n integers
a = (int*) malloc(n * sizeof(int));
if (a == NULL) { exit(1); }
// ... use the array ...
free(a); // Free the allocated memory
return 0;
}
Visualizing a 2D Dynamic Array
A 2D dynamic array in C is typically an "array of pointers," where each pointer then points to a dynamically allocated 1D array (a row). Enter dimensions below to visualize this structure.