C Pointer Arithmetic

You can do some arithmetic on pointers. When you add 1 to a pointer, it moves to the next element of its type, not to the next byte. So p + 1 for an int pointer moves 4 bytes (the size of an int).

Allowed operations

OperationMeaning
p++ / p--Move to the next / previous element
p + n / p - nMove n elements forward / back
p2 - p1Number of elements between two pointers
p1 == p2, p1 < p2Compare addresses

You cannot add two pointers, or multiply and divide a pointer.

Example

#include <stdio.h>

int main(void) {
    int a[] = {10, 20, 30, 40, 50};
    int *p = a;                 // points to a[0]

    printf("%d\n", *p);         // 10
    p++;
    printf("%d\n", *p);         // 20
    p = p + 2;
    printf("%d\n", *p);         // 40
    p--;
    printf("%d\n", *p);         // 30
    return 0;
}

Output:

Output of the above program is

10
20
40
30

Distance between pointers

#include <stdio.h>

int main(void) {
    int a[] = {10, 20, 30, 40, 50};
    int *first = &a[0];
    int *last = &a[4];

    printf("Elements between: %ld\n", last - first);
    return 0;
}

Output:

Output of the above program is

Elements between: 4

Print an array using a pointer

#include <stdio.h>

int main(void) {
    int a[] = {5, 10, 15};

    for (int *p = a; p < a + 3; p++) {
        printf("%d ", *p);
    }
    printf("\n");
    return 0;
}

Output:

Output of the above program is

5 10 15

Note: Do not move a pointer outside the array. Pointing one place after the last element is allowed for comparison, but reading it is not.

Next: C Pointer to Pointer.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.