Pointer arithmetic

suggest change

Pointer addition

Adding an integer N to a pointer yields a pointer N elements past the original, measured in units of the pointed-to type. The sum is defined only when both the original pointer and the result address the same array (or one past its end).

int arr[] = {1, 2, 3, 4, 5};
printf("*(arr + 3) = %i\n", *(arr + 3)); /* Outputs "4", arr's fourth element. */

It does not matter whether the pointer or the integer is on the left, so 3 + arr is valid. If arr[k] is element k (counting from zero), then arr + k points at arr[k]. In particular, arr and arr + 0 point at arr[0], and arr + 1 points at arr[1]. In general, *(arr + k) is the same as arr[k].

Adding 1 to a pointer advances it by sizeof the pointed-to type, not by one byte. For int, that is often 4 bytes and is not required to be. An array name is not a pointer object: in this expression it converts to a pointer to the first element, and that value cannot be incremented. A separate pointer can be. For example:

#include <stdio.h>
static const size_t N = 5;

int main(void)
{
    size_t k = 0;
    int arr[] = {1, 2, 3, 4, 5};
    for(k = 0; k < N; k++)
    {
        printf("\n\t%d", *(arr + k));
    }
    return 0;
}

By defining a pointer to the array, the above program is equivalent to the following:

#include <stdio.h>
static const size_t N = 5;

int main(void)
{
    size_t k = 0;
    int arr[] = {1, 2, 3, 4, 5};
    int *ptr = arr; /* or int *ptr = &arr[0]; */
    for(k = 0; k < N; k++)
    {
        printf("\n\t%d", ptr[k]);
        /* or   printf("\n\t%d", *(ptr + k)); */
        /* or   printf("\n\t%d", *ptr++); */
    }
    return 0;
}

The pointer ptr can also be advanced or rewound with +, -, ++, and --. Those operations are defined only inside the array and one past its last element. The commented *ptr++ walks ptr itself, so it replaces the ptr[k] expression rather than running in addition to it.

Pointer subtraction

Subtracting two pointers to elements of the same array object (or one past its end) yields a ptrdiff_t equal to the number of elements from the right-hand pointer to the left-hand one. Subtracting pointers that do not address the same array is undefined behavior. ptrdiff_t is declared in <stddef.h>, and %ti is the matching printf length modifier.

int arr[] = {1, 2, 3, 4, 5};
int *p = &arr[2];
int *q = &arr[3];
ptrdiff_t diff = q - p;

printf("q - p = %ti\n", diff); /* Outputs "1". */
printf("*(p + (q - p)) = %d\n", *(p + diff)); /* Outputs "4". */

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents