Sub topic 5
Pointer arithmetic
This chapter assumes you can declare a pointer, take an address with &, and dereference with *. It also assumes you know that an array's elements sit next to each other in memory. Here you will learn what p + n, p - q, and p++ actually compute, which operations are legal, and where the behavior becomes undefined. GATE questions test these rules often.
The scaling rule
Adding an integer to a pointer moves it by whole elements, not bytes. The compiler multiplies n by the size of the pointed-to type:
address of (p + n) = address of p + n * sizeof(*p)So if p is an int * and sizeof(int) is 4, then p + 1 is 4 bytes after p. If p is a double *, p + 1 is 8 bytes after p. The expression p[i] is defined as *(p + i), so indexing is pointer arithmetic followed by a dereference.
#include <stdio.h>
#include <stddef.h>
int main(void) {
int a[4] = {10, 20, 30, 40};
int *p = a;
printf("%d %d\n", *p, *(p + 2));
p++;
printf("%d\n", *p);
printf("%td\n", &a[3] - p);
return 0;
}The program prints 10 30, then 20, then 2. After p++, p points at a[1]. The difference &a[3] - p is 3 - 1 = 2 elements.
Which operations are legal
| Expression | Meaning | Legal? |
|---|---|---|
| `p + n`, `n + p` | Pointer moved forward by `n` elements | Yes |
| `p - n` | Pointer moved back by `n` elements | Yes |
| `p - q` | Number of elements between two pointers of the same type | Yes, if both point into the same array |
| `p++`, `--p` | Move by one element | Yes |
| `p < q`, `p == q` | Compare positions | Yes (relational operators need the same array) |
| `p + q` | Sum of two addresses | No, does not compile |
| `p * 2`, `p / 2` | Scaling an address | No, does not compile |
Only addition and subtraction of integers, subtraction of two pointers, and comparisons are allowed. The reason is that adding two addresses has no meaning, but a distance between two addresses does.
Pointer difference
p - q yields a signed integer of type ptrdiff_t, declared in <stddef.h>. The value is measured in elements, not bytes. Print it with %td. To see byte distances, cast both pointers to char *, because sizeof(char) is always 1:
#include <stdio.h>
int main(void) {
double d[3] = {1.0, 2.0, 3.0};
double *p = d;
double *q = d + 2;
printf("%td\n", q - p);
printf("%zu\n", (size_t)((char *)q - (char *)p));
printf("%zu\n", 2 * sizeof(double));
return 0;
}The first line prints 2. The second and third lines print the same number, normally 16.
Walking an array with begin and end pointers
C allows a pointer to point one element past the end of an array. You may compute and compare that pointer, but you must not dereference it. This makes the common loop pattern safe:
#include <stdio.h>
int sum(const int *begin, const int *end) {
int s = 0;
for (const int *p = begin; p != end; p++) {
s += *p;
}
return s;
}
int main(void) {
int a[5] = {1, 2, 3, 4, 5};
printf("%d\n", sum(a, a + 5));
return 0;
}This prints 15. The pointer a + 5 is the one-past-the-end position. The loop stops when p reaches it and never reads it.
The string-length function from the strings chapter uses the same idea. It advances p to the terminator and returns p - s.
#include <stddef.h>
size_t my_strlen(const char *s) {
const char *p = s;
while (*p != '\0') {
p++;
}
return (size_t)(p - s);
}Special cases
void pointers
void * has no element size, so standard C does not allow p + 1 on it. Some compilers (GCC) treat sizeof(void) as 1 as an extension, but a GATE answer should treat this as an error. Cast to char * first if you need byte steps.
Pointer to an array
For int (*pa)[3], the pointed-to type is int[3], so pa + 1 moves by 3 * sizeof(int) bytes. This is why a pointer to a row of a two-dimensional array steps a whole row at a time.
Casts change the step
If int *p points to an object and you evaluate (char *)p + 1, the step is 1 byte. If you evaluate (char *)(p + 1), the step is sizeof(int) bytes. The position of the parentheses decides which one you get.
Undefined behavior
The rules below matter because the compiler may assume you never break them.
- Moving a pointer outside the array, other than to one past the end, is undefined. This holds even if you never dereference the result.
a + 6forint a[5]is already undefined. - Subtracting or comparing pointers that point into different arrays (different objects) is undefined.
- Dereferencing a one-past-the-end pointer is undefined.
- Arithmetic on a null pointer, or on a pointer to freed memory, is undefined.
Common mistakes
- Thinking
p + 1adds 1 byte. It addssizeof(*p)bytes. - Reading
p - qas bytes. It counts elements. - Expecting
p + qto compile. - Forgetting that
*(p + 1)and*p + 1differ. The first reads the next element. The second adds 1 to the current element's value. - Treating a one-past-the-end pointer as readable.
Exercise
Assume sizeof(short) is 2. Given short a[5] = {5, 10, 15, 20, 25}; short p = a + 1; short q = a + 4; what are q - p, (q - 1), (p < q), and (char )q - (char *)p?
Show answer
q - p is 3 elements. (q - 1) is a[3], which is 20. The comparison p < q is 1 (true), since both point into the same array and p is earlier. The byte difference is 3 2 = 6.
Exercise
For int a[5], is the expression int *p = a + 6; valid C if p is never dereferenced? What about a + 5?
Show answer
a + 6 is undefined behavior even without a dereference, because it is more than one past the end. a + 5 is valid to compute and compare, but dereferencing it is undefined.
Exercise
If double p points to address 1000 and sizeof(double) is 8, what address does p + 3 hold, and what value does (char )p + 3 hold as an address?
Show answer
p + 3 is 1000 + 3 8 = 1024. (char )p + 3 is 1003, because char steps are 1 byte.