cppintermediate10 minutes
Predict the Output: Multi-dimensional Array and Pointer Arithmetic in C++
Analyze the provided C++ code snippet involving multi-dimensional arrays and pointer arithmetic. Predict the output without running the code.
Challenge prompt
Consider the following C++ code snippet: int main() { int arr[2][3] = {{1, 2, 3}, {4, 5, 6}}; int *ptr = &arr[0][0]; std::cout << *(ptr + 4) << " "; std::cout << *(*(arr + 1) + 1) << " "; std::cout << arr[1][2] << " "; std::cout << *(arr[0] + 2) << std::endl; return 0; } What will be the output of this code?
Guidance
- • Remember how multi-dimensional arrays are laid out contiguously in memory in row-major order.
- • Understand pointer arithmetic and how incrementing an int pointer moves it to the next integer element.
Hints
- • The expression *(ptr + 4) accesses the 5th element from the beginning of the array.
- • The expression *(*(arr + 1) + 1) accesses the element in the second row, second column.
Starter code
int main() {
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
int *ptr = &arr[0][0];
std::cout << *(ptr + 4) << " ";
std::cout << *(*(arr + 1) + 1) << " ";
std::cout << arr[1][2] << " ";
std::cout << *(arr[0] + 2) << std::endl;
return 0;
}Expected output
5 5 6 3
Core concepts
pointer arithmeticmulti-dimensional arrays
Challenge a Friend
Send this duel to someone else and see if they can solve it.