cpp / intermediate
Snippet
Direct Memory Access via Array Pointers
In C++, arrays decay into pointers to their first element. Pointer arithmetic allows you to navigate through the array by adding offsets to the base address, which is a fundamental concept in low-level memory management.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>void modifyArray() {int values[3] = {10, 20, 30};int* ptr = values; // Array decays to pointer*(ptr + 1) = 50; // Equivalent to values[1]for (int i = 0; i < 3; i++) {std::cout << values[i] << " ";}}
Breakdown
1
int* ptr = values;
The array name acts as a constant pointer to the first element (index 0).
2
*(ptr + 1) = 50;
Dereferences the address at (base + size of int) to modify the second element.