Pointer Arithmetic in C

Pointer Arithmetic in C


Introduction

Pointer arithmetic allows us to perform operations on pointers.
It is mainly used with arrays and helps in efficient memory access.

👉 Instead of using indexing, we can use pointer arithmetic to access elements.


What is Pointer Arithmetic?

Pointer arithmetic means:
👉 Performing mathematical operations on pointers


Allowed Operations

  • ✔ Addition (+)
  • ✔ Subtraction (-)
  • ✔ Increment (++)
  • ✔ Decrement (--)

1. Pointer Increment

#include <stdio.h>

int main() {
int arr[] = {10, 20, 30};
int *ptr = arr;

printf("%d\n", *ptr);
ptr++;
printf("%d\n", *ptr);

return 0;
}

Output

10
20

Explanation

👉 ptr++ moves pointer to next element


2. Pointer Addition

#include <stdio.h>

int main() {
int arr[] = {5, 10, 15};
int *ptr = arr;

printf("%d\n", *(ptr + 2));

return 0;
}

Output

15

3. Pointer Subtraction

#include <stdio.h>

int main() {
int arr[] = {1, 2, 3, 4};
int *p1 = &arr[3];
int *p2 = &arr[1];

printf("%ld", p1 - p2);

return 0;
}

Output

2

👉 Difference between positions


4. Pointer Decrement

#include <stdio.h>

int main() {
int arr[] = {10, 20, 30};
int *ptr = &arr[2];

printf("%d\n", *ptr);
ptr--;
printf("%d\n", *ptr);

return 0;
}

Output

30
20

Pointer Arithmetic Table

Operation Meaning Example
ptr++ Next element Move forward
ptr-- Previous element Move backward
ptr + n Move n steps Jump forward
ptr - n Move back n steps Jump backward

Important Notes

  • Pointer moves based on data type size
  • int → 4 bytes
  • char → 1 byte

Common Mistakes

  • ❌ Accessing invalid memory
  • ❌ Wrong pointer type
  • ❌ Out-of-bounds access
  • ❌ Misunderstanding pointer movement

Pro Tips

  • ✔ Use pointers with arrays
  • ✔ Understand memory layout
  • ✔ Practice pointer problems
  • ✔ Avoid unsafe operations

Conclusion

Pointer arithmetic is a powerful feature in C. It helps in efficient data access and improves performance.

👉 Master it to write optimized programs.

👉 This article is part of Dharani Tech Edu Hub — where learning programming is made simple and practical.

Comments

Popular posts from this blog

Introduction to C Programming

Operators in C

Input & Output in C