Chapter 11: Pointers Basics
Pointers are often considered the most difficult part of C, but they are also the most powerful. A pointer is simply a variable that stores the memory address of another variable. Mastering pointers is essential for efficient memory management and data structure design.
I. Understanding Memory Addresses
Every variable in your program lives at a specific location in the computer's RAM. You can find this address using the Address-of Operator (&).
int x = 10;
printf("Value of x: %d\n", x);
printf("Address of x: %p\n", (void*)&x); // %p is the format for addresses
II. Pointer Syntax: Declaration and Dereferencing
A pointer is declared by adding an asterisk (*) between the type and the name.
- Declaration:
int *ptr;(ptr is a pointer to an integer). - Assignment:
ptr = &x;(ptr now stores the address of x). - Dereferencing:
*ptr = 20;(Go to the address stored in ptr and change the value there to 20).
III. Why Use Pointers?
- Efficiency: Passing a pointer to a large structure (8 bytes) is much faster than passing a copy of the structure (potentially kilobytes).
- Dynamic Memory: Pointers allow you to allocate memory on the Heap during runtime.
- Data Structures: Linked lists, trees, and graphs are built using pointers to connect nodes.
- Hardware Access: In embedded systems, you use pointers to write directly to hardware registers.
IV. Pointer Arithmetic
You can add or subtract integers from pointers. However, the pointer doesn't move by "1 byte"—it moves by the size of the type it points to.
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr; // p points to arr[0]
p++; // p now points to arr[1] (moves by 4 bytes)
printf("%d\n", *p); // Prints 20
V. Null and Dangling Pointers
- NULL Pointer: A pointer that points to nothing (
0x0). Always initialize pointers toNULLif you don't have an address for them yet.int *p = NULL; if (p != NULL) { /* Safe to dereference */ } - Dangling Pointer: A pointer that points to a memory location that has already been freed or is no longer valid. Accessing this causes Undefined Behavior.
VI. const with Pointers
const int *p: The data is constant (you cannot change the value of x via p).int * const p: The pointer is constant (you cannot change the address stored in p).const int * const p: Both are constant.