Lesson 34: Pointers Part 1: What are Pointers?
Pointers are the most powerful and unique feature of C. A pointer is a variable that stores the memory address of another variable.
Memory and Addresses
Every byte in computer memory has a unique address (a number) assigned to it. When we declare a variable, memory is allocated, and the compiler knows its address.
| Variable | Value | Memory Address (Example) |
|---|---|---|
int x | 42 | 0x7ffee1234568 |
Pointer Declaration
To declare a pointer variable, use the dereference operator (*).
Syntax: data_type *pointer_variable_name;
The data_type specifies the type of data the pointer points to, not the type of the pointer itself (which always holds an address).
c int *ptr_to_int; // Pointer to an integer char *ptr_to_char; // Pointer to a character (or string) double *ptr_to_double; // Pointer to a double
Operators for Pointers
1. Address-of Operator (&)
Returns the memory address of a variable.
2. Dereference/Indirection Operator (*)
Accesses the value stored at the memory address held by the pointer.
c int x = 100; int *p;
// 1. Assign the address of x to p p = &x;
// 2. Access the value at the address stored in p printf("Value of x: %d\n", *p); // Output: 100
// Change the value of x using the pointer *p = 200; printf("New value of x: %d\n", x); // Output: 200