C Pointers
A pointer is a variable that stores the memory address of another variable. Pointers are one of the most powerful parts of C.
Memory Addresses
Every variable lives somewhere in memory, and that place has an address. Use & to get it:
Example
#include <stdio.h>
int main(void) {
int age = 21;
printf("Value: %d\n", age);
printf("Address: %p\n", (void *) &age);
return 0;
}Value: 21 Address: 0x7ffd5e3c9a4c
The address is a hexadecimal number. It will be different on your computer, and it changes each time you run the program.
Creating a Pointer
Put * after the type to make a pointer variable:
Example
#include <stdio.h>
int main(void) {
int price = 500;
int *ptr = &price; // ptr holds the address of price
printf("%d\n", *ptr); // read the value through the pointer
*ptr = 650; // change the value through the pointer
printf("%d\n", price);
return 0;
}500 650
| Symbol | In a declaration | In an expression |
|---|---|---|
* | int *p makes a pointer | *p gives the value at the address (dereference) |
& | &x gives the address of x |
Think of a pointer as a house address written on a paper. & writes the address down, and * goes to the house to see what is inside.
Pointers and Functions
Because C passes copies, a function cannot change your variables. Pass a pointer and it can:
Example
#include <stdio.h>
void addBonus(int *salary, int bonus) {
*salary = *salary + bonus;
}
int main(void) {
int salary = 40000;
addBonus(&salary, 5000);
printf("New salary: %d\n", salary);
return 0;
}New salary: 45000
This is exactly why scanf("%d", &x) needs &: scanf must know where to put the value.
Swapping Two Values
Example
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
int x = 3, y = 8;
swap(&x, &y);
printf("x = %d, y = %d\n", x, y);
return 0;
}x = 8, y = 3
Pointers and Arrays
The name of an array works like a pointer to its first item. Adding 1 to the pointer moves to the next item:
Example
#include <stdio.h>
int main(void) {
int nums[3] = {10, 20, 30};
int *p = nums;
printf("%d\n", *p);
printf("%d\n", *(p + 1));
printf("%d\n", *(p + 2));
return 0;
}10 20 30
*(p + 1) and nums[1] mean the same thing.
NULL Pointers
A pointer that points to nothing should be set to NULL. Always check before using it:
Example
int *data = NULL;
if (data != NULL) {
printf("%d\n", *data);
}Using a pointer that is NULL or not set up crashes the program, often with a "segmentation fault".
Exercise
Exercise
If int *p = &x; which expression gives the value stored in x?
