Pointers
- A pointer is a variable that stores a memory address
i.e. it holds the location of a value - They help system remember where something is in memory
The & Operator
&var→ gives memory address ofvar
int total = 42;
printf("%p\n", (void*)&total); // prints address of totalp = &total→ stores address oftotalin pointerp
The * Operator
- If a pointer stores an address,
*pgives the item stored at that address
p→ “where” (the address)
*p→ “what” (the value at that address)
Arrays and Pointers
- An array’s name is a pointer to its first element
These are equivalent:
int totals[5];
int *p = &totals[0];
int *q = totals; // same as abovePointer Arithmetic
Pointers can move across memory:
p++→ move pointer to the next element of its type- If
ppoints to an int at address 1000, andsizeof(int)=4, thenp++makes it point to 1004
- If
#define N 5
int totals[N];
int *p = totals;
for(int i=0; i<N; i++) {
*p = i; // set value
p++; // move to next integer
}Combining * and p++:
*p++→ set value pointed at to 0 and movepto next element
Functions and Pointers
- Pointers let functions change variables outside themselves
void addOne(int *n) {
*n = *n + 1; // change the value at the address
}
int main() {
int x = 5;
addOne(&x);
printf("%d\n", x); // prints 6
}Pointer Functionality in Functions:
- Used for modifying variables in functions
- Since normal function parameters are copies
- Essential for: swapping values, updating arrays, managing dynamic memory
Pointers can be used to give functions direct access to something in memory