Memory • Addresses • Dereferencing • Pointer Arithmetic
A pointer is a variable that stores the memory address of another variable.
Every variable lives somewhere in RAM. A pointer tells us where that place is.
Two key terms:
The * is used while declaring a pointer variable.
#includeint main() { int a = 10; int *p = &a; // pointer storing address of a printf("Value of a = %d\n", a); printf("Address of a = %p\n", &a); printf("Pointer p stores = %p\n", p); printf("Value at pointer p = %d\n", *p); return 0; }
Dereferencing means accessing the value stored at the pointer’s address.
#includeint main() { int x = 25; int *ptr = &x; printf("x = %d\n", x); printf("*ptr = %d\n", *ptr); // same value as x return 0; }
You can modify a variable through a pointer.
#includeint main() { int n = 5; int *p = &n; *p = 100; // changes n printf("n = %d\n", n); return 0; }
Pointers can move between memory locations. When you add 1 to an int*, it moves by 4 bytes.
#includeint main() { int arr[3] = {10, 20, 30}; int *p = arr; // points to arr[0] printf("%d\n", *p); // 10 printf("%d\n", *(p+1)); // 20 printf("%d\n", *(p+2)); // 30 return 0; }
Functions normally get a copy of variables. Pointers allow the function to modify the original value.
#includevoid change(int *x) { *x = 200; } int main() { int n = 10; change(&n); printf("n = %d\n", n); return 0; }
| Symbol | Meaning |
|---|---|
| & | Gets address of a variable |
| * | Gets value at a memory address |
| int *p | Pointer to an int |
| p + 1 | Moves to next integer location |