Why do we use pointers in C?
A pointer is also stored in memory like any other variable. The difference is that a normal variable stores a value, while a pointer stores the address of another place in memory.
Chart 1: value and pointer in memory
Here, value is stored at address 42 and contains 98765. The pointer ptr is stored at address 68 and contains 42, so it points to value.
Chart 2: pointer to an array with 15 elements
The array occupies many memory cells. The pointer is still just one separate variable. It stores only the address of the first array element.
Example 1: copying a large array vs passing a pointer
In C, arrays are usually passed as pointers. To clearly demonstrate the cost of copying, we wrap the array inside a structure. Passing the structure by value copies the whole array, while passing a pointer only sends its memory address.
#include <stdio.h>
#define SIZE 1000000
typedef struct {
int data[SIZE];
} BigArray;
// Full copy of the whole structure
long long sum_by_copy(BigArray arr) {
long long sum = 0;
for (int i = 0; i < SIZE; i++) {
sum += arr.data[i];
}
return sum;
}
// Only the address is passed
long long sum_by_pointer(const BigArray *arr) {
long long sum = 0;
for (int i = 0; i < SIZE; i++) {
sum += arr->data[i];
}
return sum;
}
int main() {
BigArray arr;
for (int i = 0; i < SIZE; i++) {
arr.data[i] = 1;
}
printf("sum_by_copy = %lld\n", sum_by_copy(arr));
printf("sum_by_pointer = %lld\n", sum_by_pointer(&arr));
return 0;
}
The first function receives a complete copy of the large array, which is expensive. The second function receives only a pointer, so it can read the same data without duplicating it.
Example 2: modifying the original array through a pointer
Pointers also let functions directly modify the original data. This avoids copying and allows multiple parts of a program to work on the same array.
#include <stdio.h>
#define SIZE 5
void fill_with_zero(int *arr, int size) {
for (int i = 0; i < size; i++) {
arr[i] = 0;
}
}
int main() {
int big_array[SIZE] = {10, 20, 30, 40, 50};
fill_with_zero(big_array, SIZE);
for (int i = 0; i < SIZE; i++) {
printf("%d ", big_array[i]);
}
printf("\n");
return 0;
}