C Pointer Arithmetic

1. What is Pointer Arithmetic?

  • Pointer arithmetic allows you to move a pointer through memory based on the size of the data type it points to.

  • You can perform arithmetic operations like:

  1. Increment: ptr++ → points to the next element

  2. Decrement: ptr-- → points to the previous element

  3. Addition: ptr + n → points to n elements ahead

  4. Subtraction: ptr - n → points to n elements back

  5. Difference: ptr1 - ptr2 → number of elements between two pointers

Important: Pointer arithmetic automatically accounts for the size of the data type.


2. Basic Example with int Array


 

Output:

Pointer points to: 10
Pointer points to: 20
Pointer points to: 40
Pointer points to: 30

Notice how pointer moves by 4 bytes each time (for int) on most systems.


3. Pointer Arithmetic with Array Indexing

  • Array indexing is equivalent to pointer arithmetic:



 

  • numbers + 2 → address of 3rd element

  • *(numbers + 2) → value at that address


4. Difference Between Two Pointers


 

Output:

Number of elements between ptr2 and ptr1: 3

Subtracting pointers gives the number of elements, not bytes.


5. Pointer Arithmetic with char Array (String)


 

Output:

H
e
o

For char, each pointer increment moves 1 byte (size of char).


6. Key Points About Pointer Arithmetic

  1. Only valid on pointers to elements of an array or contiguous memory.

  2. ptr++ moves to the next element (not next byte).

  3. ptr + n moves n elements forward.

  4. Subtracting pointers gives distance in elements, not bytes.

  5. Works for int, char, float, double, etc., adjusting automatically for size.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *