Back to course

Pointers Part 3: Pointer Arithmetic

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 36: Pointers Part 3: Pointer Arithmetic

Pointer arithmetic allows us to move a pointer forward or backward through contiguous memory blocks, typically arrays.

The Rule of Pointer Arithmetic

When you add an integer $N$ to a pointer, the address increases not by $N$ bytes, but by $N$ times the sizeof() the data type the pointer points to.

New Address = Current Address + (N * sizeof(data_type))

Example

Assume int is 4 bytes. p starts at address 1000.

c int arr[3] = {10, 20, 30}; int *p = arr; // p is at address 1000

p++; // p moves to the next integer element (address 1004)

printf("%d\n", *p); // Output: 20

p = p + 2; // p moves two integers forward (address 1004 + 8 = 1012) printf("%d\n", *p); // Output: 30

Operations Allowed on Pointers

  1. Addition/Subtraction of an Integer: Moves the pointer location.
  2. Increment/Decrement (++, --): Moves the pointer to the next/previous element.
  3. Subtraction of Two Pointers: Calculates the number of elements between two pointers (the result is an integer, often of type ptrdiff_t).
  4. Comparison: Pointers can be compared (==, !=, >, etc.). This is meaningful only if they point to elements within the same array.

Void Pointers

A void * pointer can hold the address of any data type. It is useful for general memory operations. However, you cannot dereference or perform arithmetic directly on a void * because the compiler doesn't know the size of the data it points to.