c++ how to pass a 2d array into a function with 2 variables representing it's dimensions
- User
c++ how to pass a 2d array into a function with 2 variables representing it's dimensions
- Assistant
To pass a 2D array into a function along with its dimensions in C++, you can do so by specifying both dimensions as separate variables in the function's parameter list. Here's an example:
#include <iostream> // Function to process 2D array with its dimensions void processArray(int** arr, int rowCount, int colCount) { for (int i = 0; i < rowCount; ++i) { for (int j = 0; j < colCount; ++j) { // Access and print array elements std::cout << arr[i][j] << " "; } std::cout << std::endl; } } int main() { // Example 2D array int rowCount = 3; int colCount = 4; int** arr = new int*[rowCount]; for (int i = 0; i < rowCount; ++i) { arr[i] = new int[colCount]; for (int j = 0; j < colCount; ++j) { arr[i][j] = i * colCount + j; } } // Pass the array and its dimensions to the function processArray(arr, rowCount, colCount); // Deallocate the memory for (int i = 0; i < rowCount; ++i) { delete[] arr[i]; } delete[] arr; return 0; }In this example, the function
processArraytakes three parameters:int** arrfor the 2D array,int rowCountfor the number of rows, andint colCountfor the number of columns. It then iterates over the array's indices, accessing and printing the array elements.In the
mainfunction, a sample 2D array is created, and its dimensions are passed along with the array itself to theprocessArrayfunction. Finally, memory is deallocated to avoid memory leaks.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.