A pointer is a special type of variable that stores the memory address of another variable. Understanding pointers is essential because they enable C to manage memory dynamically, implement complex data structures, and pass arguments efficiently.
1. The Core Concept: Memory Addresses
Every variable in your program resides at a unique location in the computer’s RAM. That location is identified by its memory address.
2. Declaring Pointer Variables
To declare a pointer, you must use the dereference operator (*) before the variable name. This tells the compiler that the variable will store an address, not a regular value. You must also specify the type of data the pointer will point to.
Syntax: dataType *pointerName;
int *p_age; // Pointer to an integer
float *p_score; // Pointer to a float
char *p_initial; // Pointer to a character
3. Essential Pointer Operators
Two operators are crucial for working with pointers:
| Operator | Name | Purpose | Example |
& | Address-of (Reference) | Returns the memory address of a variable. | &age |
* | Dereference (Indirection) | Accesses the value stored at the address contained in the pointer variable. | *p_age |
4. Initialization and Use
Pointers are typically used in three steps:
- Declare the pointer.
- Assign it the address of a variable using the
&operator. - Access or modify the original variable’s value using the
*operator (dereference).
Example Workflow
int age = 25; // Regular integer variable
int *p_age; // Pointer to an integer
// 1. Assign the address: p_age now stores the memory location of 'age'
p_age = &age;
// 2. Dereference to print the value stored at the address
printf("The value stored at address %p is: %d\n", p_age, *p_age);
// Note: %p is the format specifier for printing addresses (pointers)
// 3. Use the pointer to CHANGE the original variable's value
*p_age = 30;
// 'age' has now been changed to 30 via the pointer
printf("New age value: %d\n", age);
5. The Null Pointer
A pointer that is not pointing to a valid memory location should be initialized to NULL. This is a defined constant that represents the address zero (an address that should never be used for user data).
- Purpose: Initializing to
NULLprevents the pointer from pointing to a random, potentially dangerous memory location (dangling pointer).
int *p_data = NULL;
// Always check if a pointer is NULL before dereferencing it
if (p_data != NULL) {
// Safely use the pointer
}
