๐ 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.
#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; }
๐ก How It Works
ptr++
moves to the next memory location (depends on data type size).ptr--
moves back one memory slot.ptr + n
jumpsn
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.