Pointer Arithmetic in C with Examples

Pointers are one of the standout features of the C programming language. They give you direct access to memory, which makes C both powerful and adaptable. A key part of working with pointers is something called pointer arithmetic — this is where you can perform arithmetic operations on pointers to navigate through memory addresses.

pointer arithmetic in c

In this blog, we’re going to dive into pointer arithmetic in C, break down how it works, and provide some practical examples to help you really grasp the concept. Whether you’re gearing up for interviews or looking to build a solid foundation in systems-level programming, understanding this topic is essential.

Eager to master pointers, memory management, and all the core concepts of C? Check out the C Programming Course in Noida by Uncodemy for comprehensive training with hands-on practice.

What is a Pointer?

In C, a pointer is a variable that holds the memory address of another variable. You declare it using the * operator.

Example:

int a = 10;

int *ptr = &a;

In this case, ptr contains the address of the variable a.

What is Pointer Arithmetic?

Pointer arithmetic involves performing operations like addition, subtraction, incrementing, and decrementing on pointers. Unlike regular variables, these operations are based on the size of the data type that the pointer is pointing to.

You’ll mostly use pointer arithmetic with arrays, dynamic memory, and complex data structures like linked lists and trees.

Why Use Pointer Arithmetic?

-        To efficiently traverse arrays and memory blocks

-        To manipulate data structures such as matrices, stacks, and linked lists

-        To access elements dynamically and efficiently

-        To enhance performance in embedded and system programming

Types of Pointer Arithmetic in C

Here are the main operations you can perform with pointer arithmetic:

-        Pointer Addition (ptr + n)

-        Pointer Subtraction (ptr - n)

-        Pointer Increment (ptr++)

-        Pointer Decrement (ptr--)

-        Pointer Difference (ptr1 - ptr2)

Let’s take a closer look at each of these with examples.

1. Pointer Addition

When you add a number to a pointer, it moves forward by that number of elements, not bytes.

Example:

Copy Code

#include <stdio.h>

int main() {

int arr[5] = {10, 20, 30, 40, 50};

int *ptr = arr;

    printf("Original address: %p\n", ptr);

ptr = ptr + 2;

    printf("After adding 2: %p\n", ptr);

    printf("Value at new address: %d\n", *ptr);

return 0;

}

Output:

Original address: 0x7ffee6a3c910

After adding 2: 0x7ffee6a3c918

Value at new address: 30

2. Pointer Subtraction

Just like with addition, when you subtract a number from a pointer, it moves backwards in the array.

Example:

Copy Code

#include <stdio.h>

int main() {

int arr[] = {5, 10, 15, 20};

int *ptr = &arr[3];

    printf("Before subtraction: %d\n", *ptr);

ptr = ptr - 2;

    printf("After subtracting 2: %d\n", *ptr);

return 0;

}

Output:

Before subtraction: 20

After subtracting 2: 10

3. Pointer Increment and Decrement

You can use the ++ and -- operators to shift the pointer to the next or previous element in the array.

Example:

Copy Code

#include <stdio.h>

int main() {

int arr[] = {2, 4, 6};

int *ptr = arr;

    printf("Current value: %d\n", *ptr);

ptr++;

    printf("Next value: %d\n", *ptr);

ptr--;

    printf("Back to original: %d\n", *ptr);

return 0;

}

Output:

Current value: 2

Next value: 4

Back to original: 2

4. Subtracting Two Pointers

If you have two pointers that point to elements within the same array, the difference between them tells you how many elements are in between.

Example:

Copy Code

#include <stdio.h>

int main() {

int arr[] = {1, 3, 5, 7, 9};

int *ptr1 = &arr[1];

int *ptr2 = &arr[4];

int diff = ptr2 - ptr1;

    printf("Elements between ptr2 and ptr1: %d\n", diff);

return 0;

}

Output:

Elements between ptr2 and ptr1: 3

Pointer Arithmetic with Different Data Types

Copy Code

#include <stdio.h>

int main() {

char *cp;

int *ip;

double *dp;

    printf("Size of char: %lu\n", sizeof(char));

    printf("Size of int: %lu\n", sizeof(int));

    printf("Size of double: %lu\n", sizeof(double));

    printf("cp+1: %p\n", cp + 1);

    printf("ip+1: %p\n", ip + 1);

    printf("dp+1: %p\n", dp + 1);

return 0;

}

Output:

Size of char: 1

Size of int: 4

Size of double: 8

cp+1: 0x...01

ip+1: 0x...04

dp+1: 0x...08

Common Mistakes in Pointer Arithmetic

Here are some pitfalls to avoid:

1. Accessing memory out of bounds

int arr[5];

int *ptr = arr + 5; // Invalid access

2. Subtracting pointers from different arrays

int a[3], b[3];

int *p1 = a, *p2 = b;

int diff = p1 - p2; // Undefined behavior

3. Dereferencing NULL or uninitialized pointer

int *ptr;

printf("%d", *ptr); // Dangerous

Applications of Pointer Arithmetic in C

-        Pointer arithmetic is essential for:

-        Efficiently traversing arrays

-        Managing dynamic memory with malloc() and free()

-        Accessing structures through pointers

-        Manipulating strings and buffers

-        Creating custom data structures

Best Practices for Pointer Arithmetic

-        Always make sure to initialize pointers before using them

-        Stick to pointer arithmetic within the defined bounds

-        Avoid mixing different data types in your expressions

-        Use array indexing for better readability unless performance is a critical concern

-        Rely on pointer arithmetic when dealing with dynamic memory or custom data structures

Additional Example: Pointer Arithmetic with Arrays

Example:

Copy Code

#include <stdio.h>

int main() {

int arr[] = {10, 20, 30, 40};

int *ptr = arr;

for (int i = 0; i < 4; i++) {

        printf("Element %d = %d, Address = %p\n", i, *(ptr + i), (ptr + i));

}

return 0;

}

Output:

Element 0 = 10, Address = 0x7ffee12c8900

Element 1 = 20, Address = 0x7ffee12c8904

Element 2 = 30, Address = 0x7ffee12c8908

Element 3 = 40, Address = 0x7ffee12c890C

Summary Table: Pointer Arithmetic Operators

OperationDescription
ptr + nMoves pointer forward by n elements
ptr - nMoves pointer backward by n elements
ptr1 - ptr2Returns number of elements between
++ptr / ptr++Moves pointer to next element
--ptr / ptr--Moves pointer to previous element

Pointer Arithmetic and Memory Efficiency

One of the standout benefits of using pointer arithmetic in C is how it boosts memory efficiency and enhances performance. Unlike higher-level data access methods, pointer arithmetic lets programmers dive straight into memory addresses, which means they can manipulate and traverse data much more quickly.

When you're dealing with large arrays, linked lists, or intricate data structures like trees and graphs, pointer arithmetic makes it easier to navigate with minimal overhead. Instead of depending on indexed access—which can involve some hidden calculations—using pointers allows you to glide smoothly from one memory location to another, which not only speeds things up but also makes better use of resources.

Moreover, pointer arithmetic is essential for dynamic memory management. When you allocate memory at runtime (like with malloc or calloc), pointers are your only means of accessing and manipulating that dynamically allocated memory. Performing arithmetic on these pointers allows you to navigate and organize these memory segments efficiently, which would be a hassle if you relied solely on array notation.

However, while pointer arithmetic gives you greater control and efficiency, it also requires a careful approach. If misused or if boundary checks are overlooked, you could end up with memory leaks, segmentation faults, or undefined behavior. So, getting a good grasp of this technique is crucial for writing reliable, high-performance C programs.

Conclusion

Grasping pointer arithmetic in C is essential for truly mastering the language. It opens the door to low-level memory manipulation and gives you a clearer picture of how C manages data behind the scenes. Whether you're working with arrays or dynamic memory, pointer arithmetic is a fundamental concept you'll encounter frequently.

In this blog, we explored the key operations — addition, subtraction, increment, and pointer difference — all backed by straightforward examples. No matter if you're dealing with arrays, strings, or dynamic structures, mastering pointer arithmetic can significantly enhance your performance and control.

Curious to dive deeper into pointers, memory allocation, file handling, and more? Join Uncodemy’s C Programming Course in Noida for hands-on experience and expert guidance.

Frequently Asked Questions (FAQs)

Q1. What is pointer arithmetic in C?

Pointer arithmetic involves performing arithmetic operations on pointer variables, like ptr + 1 or ptr - 1, to navigate through memory addresses.

Q2. Can I perform all arithmetic operations on pointers?

Not quite. You can only do addition, subtraction, increment, and decrement. Operations like multiplication and division aren’t applicable to pointers.

Q3. How is pointer arithmetic different from normal arithmetic?

Pointer arithmetic is based on the size of the data type the pointer points to. For instance, adding 1 to an int* moves it by 4 bytes (assuming sizeof(int) is 4).

Q4. Is pointer arithmetic safe in C?

It can be safe if used properly. However, misuse can lead to undefined behavior, memory corruption, or crashes.

Q5. Can I subtract two pointers?

Yes, but only if both pointers are part of the same array or memory block. The result will tell you how many elements are between them.

Q6. What is the use of pointer arithmetic in real life?

It’s utilized in operating systems, embedded programming, file systems, memory management, and applications where performance is critical.

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses