Explain it simply
Explain it simply
A pointer is a variable whose value is an address. If a normal int variable is a box that holds a number, a pointer is a sticky note that says which box to look in. int *ptr = &age; writes the location of age on the note.
Following the note is called dereferencing, and C spells it with a star: *ptr means "the box this note points to". Reading *ptr gives you age's value, and assigning to *ptr changes age itself, even though the name age never appears in that line.
Problem → Why → Solution
The problem: a function cannot change the caller's variable
Suppose you want a helper that adds bonus points to a player's score. The obvious version below compiles and runs, yet the score printed afterwards is still 80. GCC with -Wall -Wextra even hints at the problem with parameter 'score' set but not used, because the function changes a variable that nobody ever reads again.
#include <stdio.h>
void add_bonus(int score) {
score += 10; /* changes the function's own copy only */
}
int main(void) {
int score = 80;
add_bonus(score);
printf("score = %d\n", score); /* still 80 */
return 0;
}Why doesn't the score change?
C copies every argument into the function's parameter. add_bonus receives its own int that happens to start at 80; adding 10 to that copy leaves main's score untouched, and the copy disappears when the function returns. To change main's variable, the function needs its address: void add_bonus(int *score) { *score += 10; }, called as add_bonus(&score).
Core concept: pointing, following and moving
A pointer declaration names the type it points to: int *ptr; declares ptr as a "pointer to int". The pointer variable occupies memory of its own (8 bytes on a 64-bit PC, whatever it points to), and its value is an address. You give it a value with & (ptr = &age;), by copying another pointer, or with NULL, the special value that means "points to nothing".
The star has two jobs, and keeping them apart removes most early confusion. In a declaration, int *ptr says that ptr is a pointer. In an expression, *ptr dereferences it: it names the int object at that address, so x = *ptr; reads it and *ptr = 44; writes it. Note that the star in a declaration binds to the name, not to the type, so int *a, b; makes a a pointer and b a plain int.
Dereferencing is only valid when the pointer holds the address of a live object of the right type. An uninitialized pointer contains garbage, a NULL pointer points to nothing, and a pointer to a variable whose lifetime has ended is dangling: dereferencing any of them is undefined behaviour. Being non-NULL is not proof of validity, so make it a habit to initialize every pointer, check for NULL wherever NULL is allowed, and never keep a pointer longer than its object lives.
Pointer arithmetic works in units of the pointed-to type. If p points to an int in an array, p + 1 points to the next int, sizeof(int) bytes further along, and *(p + 2) is the same as p[2]. When you use an array name in an expression it usually converts ("decays") to a pointer to its first element, which is why a function that receives an array really receives a pointer and also needs the element count. Arithmetic is only defined inside one array plus the position one past its last element, which you may compute and compare against but never dereference.
int age = 43; int *ptr = &age;
-------------------------------
ptr (8 bytes) age (4 bytes)
+---------------+ +-------+
| address of age| --------> | 43 |
+---------------+ +-------+
ptr -> the address stored in ptr
*ptr -> the int object age (read it or assign to it)
&ptr -> the address of ptr itself (type int **)- Declare: int *p holds an address
- Point: p = &x stores where x is
- Follow: *p reads or writes x
- Move: p + 1 jumps sizeof *p bytes
Before following a pointer, ask: is it initialized, is it non-NULL, and is the object still alive?
General pattern
type *ptr = NULL; /* pointer to type, pointing nowhere yet */
ptr = &variable; /* point at an existing object */
value = *ptr; /* read through the pointer */
*ptr = new_value; /* write through the pointer */
void modify(type *out) { /* lets a function change the caller's object */
if (out != NULL) *out = result;
}
modify(&variable);Always initialize a pointer, with NULL or with &variable. *ptr on the right-hand side reads, on the left-hand side it writes. A function that must change the caller's object takes a type * parameter, and the caller passes &variable.
Example: reading and changing a variable through a pointer
The program follows one int, age, through three changes. Two of them never mention age on the left side of an assignment: one writes through a local pointer, the other happens inside a function that only received age's address. Instead of printing an address, it checks ptr == &age, so the output is identical on every run.
#include <stdio.h>
void birthday(int *age_ptr) {
if (age_ptr == NULL) {
return;
}
*age_ptr = *age_ptr + 1;
}
int main(void) {
int age = 43;
int *ptr = &age;
printf("ptr points to age: %s\n", ptr == &age ? "yes" : "no");
printf("Value read through ptr: %d\n", *ptr);
*ptr = 44;
printf("age after *ptr = 44: %d\n", age);
birthday(&age);
printf("age after birthday(&age): %d\n", age);
birthday(NULL);
printf("birthday(NULL) was ignored safely\n");
return 0;
}Code breakdown
- Line 3
void birthday(int *age_ptr) {The parameter is a pointer, so the function receives the address of the caller's variable rather than a copy of its value.
- Lines 4-6
if (age_ptr == NULL) {Dereferencing NULL is undefined behaviour, so the function checks first and simply returns. Line 23 exercises this path.
- Line 7
*age_ptr = *age_ptr + 1;The *age_ptr on the right reads the current value; the *age_ptr on the left writes the result back into the caller's variable.
- Line 12
int *ptr = &age;This * is part of a declaration, so it says ptr is a pointer; nothing is dereferenced. &age is the address stored in ptr.
- Line 17
*ptr = 44;Here * is in an expression, so this writes into the object ptr points to. The next line prints age and shows 44.
- Line 20
birthday(&age);Passing age's address lets the function change main's own variable, which becomes 45.
ptr points to age: yes
Value read through ptr: 43
age after *ptr = 44: 44
age after birthday(&age): 45
birthday(NULL) was ignored safelyPointer arithmetic and walking an array
Because p + 1 moves by one element, a pointer can walk an array just like an index can. The sum() function below takes the classic pointer-plus-count pair, computes end as one past the last element and loops until p reaches it. The const in const int *values promises that sum() only reads the elements, and the compiler rejects any attempt to write through values.
#include <stddef.h>
#include <stdio.h>
int sum(const int *values, size_t count) {
int total = 0;
const int *end = values + count; /* one past the last element */
for (const int *p = values; p != end; p++) {
total += *p;
}
return total;
}
int main(void) {
int nums[4] = {10, 20, 30, 40};
int *p = nums; /* same as &nums[0] */
printf("*p = %d, *(p + 2) = %d\n", *p, *(p + 2));
printf("p + 1 is %td bytes after p\n", (char *)(p + 1) - (char *)p);
printf("sum of all four: %d\n", sum(nums, 4));
printf("sum of the last two: %d\n", sum(nums + 2, 2));
return 0;
}It prints *p = 10, *(p + 2) = 30, then p + 1 is 4 bytes after p, then the sums 100 and 70. Passing nums + 2 with a count of 2 hands sum() the tail of the array: the function cannot tell where the original array began, and it does not need to. The char * cast in the second printf converts the step into bytes, 4 for an int; for a double array the same expression would print 8.
Reading pointer declarations
| Declaration | Meaning |
|---|---|
| int *p; | p is a pointer to int |
| const int *p; | Points to a read-only int: *p = 1 is rejected, but p itself may move |
| int *const p = &x; | Constant pointer: p cannot move, but *p may change |
| int **pp; | Pointer to a pointer to int, used to change a pointer from inside a function |
| int *a, b; | Only a is a pointer; b is a plain int |
In real projects
Where this shows up in real projects
Pointers are how C functions return more than one result and edit data in place. The standard library is full of them: scanf() fills variables through pointers, strtol() reports where parsing stopped through a char ** parameter, and qsort() receives a pointer to the array plus a pointer to your comparison function. Your own code will use the same pattern for out-parameters, such as a parse function that returns a success flag and writes the parsed value through a pointer.
Large data is passed by pointer for speed, too. Handing a function the address of a 1 MB buffer copies 8 bytes instead of a megabyte, and a const pointer documents that the function will not modify it. Operating system APIs, embedded code that talks to hardware registers, and data structures such as linked lists and trees are all built from pointers, which is why tools like AddressSanitizer and Valgrind exist to catch invalid pointer use during testing.
Common mistakes
Common mistakes
1. Dereferencing an uninitialized pointer
int *p; *p = 5; writes 5 to whatever garbage address p happens to hold. GCC -Wall reports 'p' is used uninitialized, but only when it can see the problem; in more complex code it stays silent. Initialize every pointer, with a real address or with NULL, where you declare it.
2. Expecting int* a, b; to declare two pointers
The star belongs to a, so b is a plain int. Assigning an address to b is a compile error in current GCC versions: assignment to 'int' from 'int *' makes integer from pointer without a cast. Write int *a, *b; or, clearer still, one declaration per line.
3. Mixing up *p++ and (*p)++
*p++ reads the value and then moves the pointer to the next element, because ++ binds more tightly than *. To increment the value being pointed at, write (*p)++ or *p += 1.
4. Treating any non-NULL pointer as valid
A NULL check rules out only one bad value. A pointer to freed memory, or to a local of a function that has returned, is non-NULL and still invalid, so the real protection is controlling lifetimes, not adding more if statements.
Best practices
Best practices
- Initialize pointers where you declare them, using NULL when there is nothing to point at yet.
- Use const T * for parameters that only read, so both readers and the compiler know the data is not modified.
- Pass a pointer together with an element count, and keep arithmetic between the start and one past the end.
Mini challenge
Mini challenge: min, max and swap through pointers
Write two pointer-based helpers and use them on an array of temperatures.
- int min_max(const int *values, size_t count, int *min_out, int *max_out) writes the smallest and largest values through the out-pointers and returns 1
- It returns 0 without touching the outputs when values or an output pointer is NULL, or when count is 0
- Walk the array with a pointer (p++), not with an index
- void swap(int *a, int *b) exchanges two ints; use it to swap the min and max you found
#include <stddef.h>
#include <stdio.h>
int min_max(const int *values, size_t count, int *min_out, int *max_out) {
// TODO: return 0 for NULL pointers or count == 0
// TODO: start lo/hi at the first element, then walk the rest with a pointer
// TODO: write the results through min_out and max_out, then return 1
}
void swap(int *a, int *b) {
// TODO: exchange the two values using a temporary int
}
int main(void) {
int temps[] = {31, 27, 35, 24, 33};
// TODO: call min_max with &lo and &hi, print them, swap them, print again
// TODO: show what happens with a count of 0
return 0;
}Expected: The output should be: min = 24, max = 35 after swap: lo = 35, hi = 24 empty input: no result
Show hint
The loop can be for (const int *p = values + 1; p < values + count; p++). In main, declare int lo = 0, hi = 0; and call min_max(temps, n, &lo, &hi), computing n as sizeof temps / sizeof temps[0].
Show solution
#include <stddef.h>
#include <stdio.h>
int min_max(const int *values, size_t count, int *min_out, int *max_out) {
if (values == NULL || count == 0 || min_out == NULL || max_out == NULL) {
return 0;
}
int lo = *values;
int hi = *values;
for (const int *p = values + 1; p < values + count; p++) {
if (*p < lo) lo = *p;
if (*p > hi) hi = *p;
}
*min_out = lo;
*max_out = hi;
return 1;
}
void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
int main(void) {
int temps[] = {31, 27, 35, 24, 33};
size_t n = sizeof temps / sizeof temps[0];
int lo = 0, hi = 0;
if (min_max(temps, n, &lo, &hi)) {
printf("min = %d, max = %d\n", lo, hi);
}
swap(&lo, &hi);
printf("after swap: lo = %d, hi = %d\n", lo, hi);
if (!min_max(temps, 0, &lo, &hi)) {
printf("empty input: no result\n");
}
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A pointer stores an address; int *p = &x; makes p point at x.
- In a declaration * marks a pointer; in an expression *p reads or writes the object it points to.
- Pass &variable to a pointer parameter when a function must change the caller's data, and check for NULL when NULL is allowed.
- p + 1 moves by sizeof *p bytes; stay inside the array and its one-past-the-end position.
- Never dereference an uninitialized, NULL or dangling pointer.
SEI CERT C Coding Standard — Carnegie Mellon SEI