Back to C++
2026-01-127 min read

Example 2: Passing Multidimensional Array to a Function (C++)

Learn Example 2: Passing Multidimensional Array to a Function (C++) step by step with clear examples and exercises.

Title: Passing Multidimensional Arrays to Functions in C++ (With Examples)

Why This Matters

Understanding how to pass multidimensional arrays to functions is crucial for any seasoned C++ programmer. It enables writing modular, maintainable, and debuggable code. In interviews, you may encounter questions testing your knowledge of this concept, or you might face real-world bugs that require understanding of passing multidimensional arrays as function parameters.

Importance of Multidimensional Array Passing in C++

  1. Modularity: Functions allow us to break down complex problems into smaller, manageable parts, making the code more maintainable and easier to understand.
  2. Reusability: By creating reusable functions, we can save time by avoiding duplicated code and make our programs more efficient.
  3. Debugging: Functions help isolate issues, making it easier to identify and fix bugs in our code.
  4. Performance: Passing arrays by reference instead of value can significantly improve the performance of our programs, especially when dealing with large datasets.

Prerequisites

Before diving into the core concept, ensure you have a solid grasp of:

  1. C++ basics (variables, data types, operators, control structures)
  2. Arrays in C++
  3. Function definitions and calls in C++
  4. Passing arrays as function parameters (single-dimensional arrays)
  5. Understanding the difference between value-passing and reference-passing
  6. Basic concepts of memory management in C++
  7. Understanding pointers and their role in handling multidimensional arrays

Core Concept

A multidimensional array is an extension of a single-dimensional array, where each element is itself an array. In C++, we can declare a 2D array like this:

int arr[3][4]; // Declaring a 2D array with 3 rows and 4 columns

Passing a multidimensional array to a function is similar to passing a single-dimensional array. The function signature should include the array as a parameter, which can be passed by value or by reference.

Value Passing vs Reference Passing

When passing an array by value, the entire array contents are copied into the function's memory space. This can lead to performance issues when dealing with large arrays. On the other hand, passing an array by reference allows the function to operate directly on the original data in the caller's memory space.

void printArray(int arr[][4]); // Function declaration (array passed by value)
void printArray(int (&arr)[3][4]); // Function declaration (array passed by reference)

In both cases, when calling the function, we pass the array:

printArray(arr); // Function call with our 2D array

Accessing Multidimensional Arrays Inside Functions

When passing an array by value, access the elements using nested loops inside the function:

void printArray(int arr[][4]) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 4; ++j) {
cout << arr[i][j] << " "; // Printing each element
}
cout << endl; // Printing a newline after each row
}
}

When passing an array by reference, access the elements directly:

void printArray(int (&arr)[3][4]) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 4; ++j) {
cout << arr[i][j] << " "; // Printing each element
}
cout << endl; // Printing a newline after each row
}
}

Understanding Pointers and Multidimensional Arrays

To better understand multidimensional arrays, it's essential to grasp the role of pointers in handling them. A 2D array can be thought of as an array of pointers, where each pointer points to a single-dimensional array:

int arr[3][4]; // Declaring a 2D array
// Equivalent representation using pointers:
int* arrPtr = new int[3 * 4]; // Allocating memory for the entire 2D array
int(*arr2D)[4] = reinterpret_cast<int(*)[4]>(arrPtr); // Casting the pointer to a 2D array

Passing Multidimensional Arrays by Reference Using Pointers

To pass a multidimensional array by reference using pointers, we can create a function that accepts a pointer to the first element of the array:

void printArray(int arr[][4], int rowSize) {
// Accessing the elements directly using pointers
for (int i = 0; i < rowSize; ++i) {
for (int j = 0; j < 4; ++j) {
cout << *(arr + i * 4 + j) << " "; // Printing each element
}
cout << endl; // Printing a newline after each row
}
}

Worked Example

Consider the following C++ program that initializes a 2D array, passes it to a function (both by value and by reference), and prints its contents:

#include <iostream>
using namespace std;

// Function declaration (array passed by value)
void printArrayByValue(int arr[][4], int rowSize);

// Function declaration (array passed by reference using pointers)
void printArrayByRefPtr(int* arr, int rowSize, int colSize);

int main() {
int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; // Initializing the 2D array

printArrayByValue(arr); // Printing the array by value
cout << endl;

printArrayByRefPtr(arr, 3, 4); // Printing the array by reference using pointers

return 0;
}

void printArrayByValue(int arr[][4], int rowSize) {
// Accessing the elements using nested loops
for (int i = 0; i < rowSize; ++i) {
for (int j = 0; j < 4; ++j) {
cout << arr[i][j] << " "; // Printing each element
}
cout << endl; // Printing a newline after each row
}
}

void printArrayByRefPtr(int* arr, int rowSize, int colSize) {
// Accessing the elements directly using pointers
for (int i = 0; i < rowSize; ++i) {
for (int j = 0; j < colSize; ++j) {
cout << *(arr + i * colSize + j) << " "; // Printing each element
}
cout << endl; // Printing a newline after each row
}
}

When you run this program, it should output:

1 2 3 4
5 6 7 8
9 10 11 12

1 2 3 4
5 6 7 8
9 10 11 12

Common Mistakes

  1. Forgetting to pass the row size: When passing an array by value, remember that you don't need to provide the row size as it can be inferred from the array declaration. However, when passing an array by reference, you still need to provide the row size explicitly.
// Incorrect function call: printArrayByValue(arr); (array passed by value)
void printArrayByValue(int arr[][4], int rowSize); // Function declaration (array passed by value)

// Correct function call: printArrayByRefPtr(arr, 3); (array passed by reference using pointers)
void printArrayByRefPtr(int* arr, int rowSize, int colSize); // Function declaration (array passed by reference using pointers)
  1. Incorrect loop limits: Ensure your nested loops have the correct limits for both rows and columns.
// Incorrect loop limit in the column loop: for (int j = 0; j < arrSize; ++j)
void printArray(int arr[][arrSize], int rowSize) { ... }
  1. Accessing out-of-bounds elements: Accessing an out-of-bounds element will lead to undefined behavior, which can result in runtime errors or security vulnerabilities. Always ensure you have proper bounds checking in your code.
  1. Not properly deallocating memory: When using pointers to handle multidimensional arrays, always remember to properly deallocate the memory once you're done with it to avoid memory leaks.
void printArrayByRefPtr(int* arr, int rowSize, int colSize) {
// Accessing the elements directly using pointers
for (int i = 0; i < rowSize; ++i) {
for (int j = 0; j < colSize; ++j) {
cout << *(arr + i * colSize + j) << " "; // Printing each element
}
cout << endl; // Printing a newline after each row
}
delete[] arr; // Deallocating the memory once done
}

Practice Questions

  1. Write a function that takes a 2D array and calculates the sum of all its elements.
int calculateSum(int arr[][4], int rowSize) {
int total = 0;
for (int i = 0; i < rowSize; ++i) {
for (int j = 0; j < 4; ++j) {
total += arr[i][j];
}
}
return total;
}
  1. Modify the printArray() function to accept a 3D array as input.
void printArray(int arr[][4][5], int rowSize, int colSize1, int colSize2) {
for (int i = 0; i < rowSize; ++i) {
for (int j = 0; j < colSize1; ++j) {
for (int k = 0; k < colSize2; ++k) {
cout << arr[i][j][k] << " "; // Printing each element
}
cout << endl; // Printing a newline after each row
}
cout << endl; // Printing a newline after each column
}
}
  1. Write a function that sorts a 2D array using quicksort.
void quickSort(int arr[][4], int left, int right) {
if (left < right) {
int pivotIndex = partition(arr, left, right);
quickSort(arr, left, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, right);
}
}

int partition(int arr[][4], int left, int right) {
int pivot = arr[right][3]; // Choose the last element as pivot
int i = left - 1;
for (int j = left; j <= right - 1; ++j) {
if (arr[j][3] < pivot) {
++i;
swap(arr[i], arr[j]); // Swap elements to maintain the sorted sequence
}
}
swap(arr[i + 1], arr[right]); // Place the pivot in its correct position
return i + 1;
}

FAQ

  1. Can I pass a multidimensional array to a function without specifying the row size?
  • Yes, when passing an array by value, you don't need to provide the row size as it can be inferred from the array declaration. However, when passing an array by reference, you still need to provide the row size explicitly.
  1. What happens if I try to access an out-of-bounds element in a multidimensional array?
  • Accessing an out-of-bounds element will lead to undefined behavior, which can result in runtime errors or security vulnerabilities. Always ensure you have proper bounds checking in your code.
  1. Why should I use pointers when working with multidimensional arrays?
  • Pointers offer more flexibility and efficiency when handling multidimensional arrays. They allow us to dynamically allocate memory, pass arrays by reference, and manipulate the array elements directly without using nested loops.
  1. How can I efficiently implement a function that sorts a 2D array using a sorting algorithm like quicksort?
  • Implementing a quicksort function for a 2D array requires partitioning the array around a pivot element and recursively applying the sorting process to the left and right subarrays. You can use nested loops or pointers to traverse the array during the partitioning step.
Example 2: Passing Multidimensional Array to a Function (C++) | C++ | XQA Learn