Pointers
Pointers in C
A pointer stores the memory address of another variable. Pointers are central to C — they enable dynamic memory, efficient array passing, and data structures.
Address-of operator &
Returns the address of a variable:
int x = 10;
int *p = &x; // p holds the address of xDereference operator *
Access the value at an address:
printf("%d\n", *p); // prints 10
*p = 20; // modifies x through pPointer arithmetic
Adding 1 to a pointer moves it by sizeof(type) bytes — to the next array element:
int arr[] = {10, 20, 30};
int *p = arr;
printf("%d\n", *(p + 1)); // 20Passing pointers to functions Pass pointers to modify the caller's variables (simulate pass-by-reference):
void swap(int *a, int *b) {
int tmp = *a; *a = *b; *b = tmp;
}
swap(&x, &y);Key points:
- An uninitialised pointer is a wild pointer — always initialise to
NULLor a valid address. - Array names decay to a pointer to the first element.
NULLis the null pointer constant; dereferencing it is undefined behaviour.
Code Examples
#include <stdio.h>
int main(void) {
int x = 42;
int *p = &x;
printf("x = %d\n", x);
printf("address of x = %p\n", (void*)p);
printf("value via pointer = %d\n", *p);
*p = 100;
printf("x after *p=100: %d\n", x);
// Pointer arithmetic over array
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
for (int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i));
}
printf("\n");
return 0;
}& gets the address; * dereferences it. Modifying *p modifies x directly. Pointer arithmetic steps by element size.
#include <stdio.h>
void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
void reverseArray(int *arr, int n) {
int *left = arr;
int *right = arr + n - 1;
while (left < right) {
swap(left, right);
left++;
right--;
}
}
int main(void) {
int x = 5, y = 10;
printf("Before: x=%d y=%d\n", x, y);
swap(&x, &y);
printf("After: x=%d y=%d\n", x, y);
int arr[] = {1, 2, 3, 4, 5};
reverseArray(arr, 5);
for (int i = 0; i < 5; i++) printf("%d ", arr[i]);
printf("\n");
return 0;
}Passing &x and &y lets swap modify the originals. Pointer arithmetic with left++ and right-- moves through the array.
Quick Quiz
1. What does the `&` operator return?
2. What does `*(ptr + 1)` access?
Was this lesson helpful?