Pointer Arithmetic

Navigating memory with pointers

Interview Relevant: Low-level programming

Pointer Arithmetic

Pointers can be incremented/decremented to navigate memory.

Code Examples

Pointer arithmetic for array navigation.

cpp
1int arr[] = {10, 20, 30, 40, 50};
2int* ptr = arr;  // Points to first element
3
4// Increment moves by sizeof(type)
5ptr++;          // Now points to arr[1]
6cout << *ptr;   // 20
7
8// Pointer arithmetic
9cout << *(ptr + 2);  // arr[3] = 40
10cout << ptr[2];      // Same as *(ptr + 2)
11
12// Difference between pointers
13int* end = arr + 5;
14ptrdiff_t diff = end - arr;  // 5
15
16// Iterate with pointers
17for (int* p = arr; p != arr + 5; p++) {
18    cout << *p << " ";
19}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In