Topic 41 of 83
Pointer Arithmetic
Overview
Pointer arithmetic allows you to add or subtract integers from pointers to navigate through contiguous memory blocks, like arrays. It moves by the size of the data type.
Syntax
cpp
int arr[3] = {10, 20, 30};
int* ptr = arr;
cout << *ptr; // 10
ptr++; // Move to next int (adds 4 bytes to address)
cout << *ptr; // 20
cout << *(ptr + 1); // 30Common Pitfalls
- Using pointer arithmetic on pointers that don't point to arrays. Moving past a single isolated variable points to garbage memory.
Interview Tips
- Explain exactly what `ptr++` does. If `ptr` is an `int*` pointing to address `1000`, `ptr++` changes it to `1004` (assuming int is 4 bytes). It does NOT change to `1001`.
Real-World Example
Traversing an array strictly using pointer arithmetic.
example
cpp
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40};
int* ptr = arr;
// Iterate 4 times
for (int i = 0; i < 4; i++) {
cout << *ptr << " ";
ptr++; // Advance the pointer
}
return 0;
}