Skip to main content

Arithmetic operations on pointers

Short answer

Allowed: p++, p--, p+n, p-n, q-p (element count), comparisons. Not allowed: addition of two pointers, multiplication, division, float addition. Example: int a[5], *p=a; p++; p+2; q-p gives element difference.

What type of arithmetic operations can be implemented in pointer? Describe with appropriate syntax and examples.

The following arithmetic operations are allowed on pointers:

OperationSyntaxMeaning
Increment / decrementp++, p--Moves to the next / previous element (by sizeof the type)
Add an integerp + nAddress of the n-th element after p
Subtract an integerp - nAddress of the n-th element before p
Subtract two pointersq - pNumber of elements between them (same array only)
Comparisonp < q, p == qCompares addresses (same array)

Not allowed: adding two pointers, multiplying or dividing a pointer, or adding a float.

#include <stdio.h>

int main(void)
{
    int a[5] = {10, 20, 30, 40, 50};
    int *p = a, *q = &a[4];

    printf("*p = %d\n", *p);
    p++;                                   /* next element */
    printf("after p++      : *p = %d\n", *p);
    p = p + 2;
    printf("after p = p + 2: *p = %d\n", *p);
    p--;
    printf("after p--      : *p = %d\n", *p);
    printf("q - p = %ld elements\n", (long)(q - p));
    printf("p < q is %d\n", p < q);
    return 0;
}

Output:

*p = 10
after p++      : *p = 20
after p = p + 2: *p = 40
after p--      : *p = 30
q - p = 2 elements
p < q is 1

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 9 questions →