Pointers are often considered the "boss level" of C, but they are actually quite simple once you realize they are just variables that store memory addresses instead of actual values.
Think of a variable as a house and a pointer as the address written on a piece of paper. The paper doesn't contain the people inside the house; it just tells you where to find them.
1. The Two Key Operators
To work with pointers, you need two special symbols:
&(Address-of): Gets the memory address of a variable.*(Value-at-address/Dereference): Gets the data stored at the address the pointer is holding.
2. Basic Pointer Code
Here is how you declare, initialize, and use a pointer.
#include <stdio.h>
int main() {
int num = 42; // A regular variable
int *ptr; // A pointer variable (the * means "this is a pointer")
ptr = # // Store the address of 'num' in 'ptr'
printf("Value of num: %d\n", num);
printf("Address of num: %p\n", (void*)&num);
printf("Value stored in ptr (Address): %p\n", (void*)ptr);
// Dereferencing: Accessing the value via the pointer
printf("Value pointed to by ptr: %d\n", *ptr);
// Changing the value through the pointer
*ptr = 100;
printf("New value of num: %d\n", num);
return 0;
}Expected Output:
Value of num: 42
Address of num: 0x7ffed3a4c12c
Value stored in ptr (Address): 0x7ffed3a4c12c
Value pointed to by ptr: 42
New value of num: 1003. Why Use Pointers?
Call by Reference: You can allow a function to modify a variable inside
main.Dynamic Memory: As we saw earlier,
mallocreturns a pointer.Arrays: In C, an array name is essentially a pointer to its first element.
Efficiency: Instead of passing a massive
struct(copying all its data), you just pass one small pointer.
4. Pointer Arithmetic
You can actually do "math" with pointers. If you increment a pointer (ptr++), it doesn't just add 1; it moves to the next memory location based on the data type size.
If
ptrpoints to anint(4 bytes),ptr++moves the address forward by 4.
5. Dangerous Pointers to Avoid
NULL Pointer: A pointer that points to nothing (
int *p = NULL;). Always check if a pointer is NULL before using it to avoid crashes.Dangling Pointer: A pointer that points to memory that has already been
free()'d.Wild Pointer: A pointer that hasn't been initialized at all. It points to a random, "wild" spot in memory.
Combining Pointers and Structures
Remember our struct Student? We can use a special arrow operator (->) to access structure members through a pointer.
struct Student s1 = {"Bob", 101, 3.5};
struct Student *ptr = &s1;
printf("Name: %s", ptr->name); // Same as (*ptr).name