- Why an array name behaves like a pointer to its first element (array decay)
- How pointer arithmetic (
p + i,p++) walks through an array - Two ways to traverse an array with a pointer: indexed and advancing
- How
*(p + i)is exactly equivalent toarr[i] - How to write the same logic as a reusable function that takes a pointer and a length
Arrays and Pointers — Why They're Related
In C, the name of an array is almost the same as a pointer to its first element. When you write int arr[5] = {10, 20, 30, 40, 50};, the expression arr — when used in a value context — decays to a pointer of type int * that holds the address of arr[0]. That decay is why arr and &arr[0] print the same address, and why you can assign int *p = arr; without any cast.
The key insight is that arr[i] is defined to be exactly *(arr + i). It's not "similar to" — it is the same operation, by the language definition. The brackets are a notational convenience. Once you accept that, iterating over an array with a pointer is the same as iterating over it with an index — except you're computing the address arithmetic explicitly rather than letting the compiler do it for you.
This program uses that relationship: get a pointer to the first element, walk it forward one element at a time, and add each element to a running total.
💡 In one line: arr[i] and *(arr + i) are the same thing. The pointer version just makes that arithmetic explicit.
Pointer Arithmetic on Arrays
| Expression | Meaning | Example (with int arr[5]; int *p = arr;) |
|---|---|---|
p | Pointer to the first element | Points at arr[0] |
p + i | Pointer offset by i elements | p + 2 points at arr[2] |
*(p + i) | Value at the offset | *(p + 2) is arr[2] |
p[i] | Same as *(p + i) | p[2] is arr[2] |
p++ | Advance pointer to next element | Moves from arr[0] to arr[1] |
*p++ | Read current value, then advance | Common idiom in loops |
p < arr + n | Loop termination check | True until p reaches one past the end |
Two rules govern pointer arithmetic. First, adding i to p advances by i * sizeof(*p) bytes — not i bytes. That's why p + 1 reaches the next int even though int is usually 4 bytes. Second, you may compute the "one-past-the-end" pointer (arr + n) and compare against it, but you must never dereference it. Stepping exactly one past the end is legal for comparison; going further is undefined behaviour.
Complete C Program
Program: sum an array's elements through a pointer, then refactor into a function
#include <stdio.h>
/* Sum n elements starting at *p using indexed pointer arithmetic */
int sum_array(const int *p, int n) {
if (p == NULL || n <= 0) {
return 0;
}
int total = 0;
for (int i = 0; i < n; i++) {
total += *(p + i); /* same as p[i] and arr[i] */
}
return total;
}
/* Sum n elements by advancing the pointer itself */
int sum_array_advancing(const int *p, int n) {
if (p == NULL || n <= 0) {
return 0;
}
const int *end = p + n; /* one-past-the-end, safe to compute */
int total = 0;
while (p < end) {
total += *p; /* read current element */
p++; /* move to next element */
}
return total;
}
int main(void) {
int arr[6] = {10, 20, 30, 40, 50, 60};
int n = 6;
/* Pointer to the first element — the array name decays to int * */
int *p = arr;
/* Indexed approach inside main */
int sum1 = 0;
for (int i = 0; i < n; i++) {
sum1 += *(p + i);
}
printf("Sum via *(p + i) = %d\n", sum1);
/* Advancing approach inside main */
int *q = arr;
int sum2 = 0;
for (int i = 0; i < n; i++) {
sum2 += *q;
q++;
}
printf("Sum via *q (advancing q)= %d\n", sum2);
/* Reusable functions */
printf("sum_array(arr, n) = %d\n", sum_array(arr, n));
printf("sum_array_advancing = %d\n", sum_array_advancing(arr, n));
return 0;
}
Program Output
Sum via *(p + i) = 210
Sum via *q (advancing q)= 210
sum_array(arr, n) = 210
sum_array_advancing = 210
All four methods compute the same total: 10 + 20 + 30 + 40 + 50 + 60 = 210. The differences are purely stylistic and syntactic — the underlying address arithmetic is identical.
Step-by-Step Explanation
Let's walk through the program, then look at the subtle points that trip people up.
1. int arr[6] = {10, 20, 30, 40, 50, 60};
The array occupies six contiguous int slots in memory. Suppose arr starts at address 0x2000 and each int is 4 bytes; then arr[0] is at 0x2000, arr[1] at 0x2004, arr[2] at 0x2008, and so on. The name arr used in an expression decays to the address 0x2000 and type int *.
2. int *p = arr;
p now holds 0x2000 and points at arr[0]. The compiler may warn if you mix types (e.g., assigning an int * to a double *) but here the types match, so no cast is needed.
3. sum1 += *(p + i);
On each iteration, p + i computes "the address i ints past p." Since p points to arr[0], p + 0 is arr[0], p + 1 is arr[1], and so on. The * operator dereferences that address to fetch the value. This is the same as writing arr[i]. On each iteration total grows by the current element.
4. sum2 += *q; q++;
A different idiom. Instead of computing p + i fresh each time, we move q itself forward by one element per step. q++ doesn't mean "add one byte"; it means "advance by one element of the pointer's type." For an int * on a typical machine that's a 4-byte jump. After the loop, q points one past the last element. This is exactly the loop-over-a-range pattern you'll see in real C code.
5. sum_array(const int *p, int n)
Wrapping the logic in a function makes it reusable. The parameter const int *p means "a pointer to const int" — the function promises not to modify the elements through p. That's a helpful contract for readers and enables the compiler to catch accidental writes. We pass arr — which decays to int * — and the compiler happily converts to const int * (adding const is allowed). Passing an explicit length n is necessary because a raw pointer does not carry the size of the array with it.
6. sum_array_advancing — the one-past-the-end idiom
Here the loop is driven by a pointer comparison rather than an index. end = p + n computes the address one element past the array's end. This is legal — you may compute one-past-the-end even though you must not dereference it. The while (p < end) condition stops exactly when p reaches end. This is idiomatic C: your loop body processes *p, then p++ moves to the next element, and the comparison halts before touching anything out of bounds.
7. Why sizeof wouldn't work here
A common beginner mistake is to try to compute n inside a function with sizeof(p) / sizeof(*p). Inside sum_array, p is a pointer (probably 8 bytes); *p is an int (probably 4 bytes). The result would be 2, not 6 — completely wrong. sizeof on an array works only in the array's own scope, where the compiler knows the declared size. Once it decays to a pointer, that information is gone. Hence passing n explicitly. (In C99+, you can use sizeof arr / sizeof arr[0] in main where arr is declared, but not inside a function that receives arr as a parameter.)
8. Const correctness — why const int *p?
When a function only reads through a pointer, marking the pointer's target const documents that promise and lets the caller pass read-only data without warnings. It also helps the compiler catch a bug like *p = 0; inside sum_array — a bug you almost certainly don't intend. The const here is part of the pointer's pointee type (const int), not of the pointer itself. A const int * can be reassigned to point elsewhere, but the int it points to cannot be modified through it.
9. Overflow — what if the sum is huge?
int typically holds up to about 2.1 billion. If the array has many large elements, the sum can overflow — undefined behaviour for signed integers. For general-purpose summing, use long long for the accumulator:
long long sum_array(const int *p, int n) {
long long total = 0;
for (int i = 0; i < n; i++) total += *(p + i);
return total;
}
This is a defensive habit worth forming early. Beginner programs rarely trigger overflow, but real data often does.
10. What if the array is empty or the pointer is NULL?
The function guards against both. If n <= 0, we return 0 without touching p. If p == NULL, likewise. Without those checks, a caller who passes an empty array would still be safe (the loop never executes), but a caller who passes NULL with n > 0 would trigger undefined behaviour — usually a segmentation fault. Two cheap checks make the function robust against common misuse.
🎯 Remember this: p + i does not add i to the address in bytes — it adds i times the size of the pointed-to type. That single fact explains almost all pointer arithmetic. And array-to-pointer decay means arr[i] and *(arr + i) are equivalent by definition, not by coincidence.
Frequently Asked Questions
1. Is arr really a pointer?
Not quite. arr is an array, and arrays are not pointers. But in most expressions, arr decays to a pointer to its first element. So int *p = arr; works because the right side decays to int *. You cannot, however, write arr = p; — arrays are not assignable. And sizeof arr gives the total size of the array (e.g., 24 bytes for 6 ints), while sizeof p gives the size of the pointer (typically 8 bytes).
2. Which is faster — p[i] or *(p + i)?
Neither. They compile to exactly the same code. The brackets are purely a notational convenience. Some people find p[i] easier to read when the index represents "position i"; others find *(p + i) clearer when the offset is meaningful. Choose what makes the intent most obvious to the next reader.
3. Can I use -1 to reach the previous element?
You can add negative offsets as long as the resulting pointer stays within the same array. If p points at arr[3], then p[-1] is arr[2]. But if you add an offset that goes outside the array's bounds, the pointer arithmetic itself is undefined behaviour — even if you never dereference. C does not guarantee anything about out-of-bounds pointer values.
4. What happens if I write while (p != end) instead of p < end?
It works fine for arrays accessed front-to-back. But while (p < end) is more robust: if something accidentally advances p past end, the != version might loop forever or walk off into memory. The < version terminates the moment p reaches end and never dereferences past it. Prefer < in general code.
5. Why does sum_array(arr, n) not need an &?
Because arr decays to a pointer. Passing arr is the same as passing &arr[0] — both are an int * that points at the first element. If you wrote &arr instead, you'd get a pointer to the entire array (type int (*)[6]), which is a different beast. The function's const int * parameter expects the decayed form, so arr is correct.
6. Can I sort or modify the array through the pointer?
Yes, as long as the parameter is not const. Writing *(p + i) = 0; modifies the array element in place, and the caller sees the change. This is exactly how functions like qsort and memset work. For summing, we use const to communicate that the function is read-only — good practice whenever possible.
💡 Tip: This "sum through a pointer" pattern generalizes immediately. Replace total += *p with if (*p > max) max = *p and you have a maximum-finder. With if (*p < min) min = *p, a minimum-finder. With if (*p == key) return i, a linear search. All of those are the next few assignments in the series — and they all use the same pointer walk.