C Pointer Arithmetic

📌 C Pointer Arithmetic

Pointer arithmetic in C lets you perform operations on memory addresses — like adding or subtracting values from pointers. This is super handy when working with arrays or memory manipulation.

🔹 What is Pointer Arithmetic?

In C, you can use operators like ++, --, +, and - with pointers. But remember: pointer arithmetic moves in steps of the size of the data type!

📝 Example: Basic Pointer Arithmetic

This example shows how pointers move through an integer array using arithmetic.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
printf("Current value: %d\n", *ptr); // 10
ptr++; // Move to next element
printf("After ptr++: %d\n", *ptr); // 20
ptr += 2; // Move 2 steps ahead
printf("After ptr += 2: %d\n", *ptr); // 40
ptr--; // Go back one step
printf("After ptr--: %d\n", *ptr); // 30
return 0;
}
#include <stdio.h> int main() { int arr[] = {10, 20, 30, 40, 50}; int *ptr = arr; printf("Current value: %d\n", *ptr); // 10 ptr++; // Move to next element printf("After ptr++: %d\n", *ptr); // 20 ptr += 2; // Move 2 steps ahead printf("After ptr += 2: %d\n", *ptr); // 40 ptr--; // Go back one step printf("After ptr--: %d\n", *ptr); // 30 return 0; }
#include <stdio.h>

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

    printf("Current value: %d\n", *ptr);   // 10
    ptr++;  // Move to next element
    printf("After ptr++: %d\n", *ptr);    // 20
    ptr += 2;  // Move 2 steps ahead
    printf("After ptr += 2: %d\n", *ptr); // 40
    ptr--;  // Go back one step
    printf("After ptr--: %d\n", *ptr);    // 30

    return 0;
}
  

Try It Now

💡 How It Works

  • ptr++ moves to the next memory location (depends on data type size).
  • ptr-- moves back one memory slot.
  • ptr + n jumps n elements forward.

🔍 Note on Types

If you’re working with int, then ptr++ increases the address by sizeof(int) (usually 4 bytes).

🛠️ Practice Time!

Try using pointer arithmetic on a char array or even a float array. See how the steps differ based on type size!

📚 Summary

  • Pointer arithmetic lets you navigate through memory.
  • Always be aware of the data type — it affects address movement!
  • Use it wisely while looping through arrays or working with dynamic memory.