Implementing a Function to Return a 2D Array in C
The provided code snippet attempts to return a 2D array from a function, but it has an issue with the array declaration. To rectify this, we can introduce a more comprehensive solution:
#include <iostream> using namespace std; // Returns a pointer to a newly created 2D array with dimensions [height x width] int** MakeGridOfCounts(int height, int width) { int** grid = new int*[height]; // Dynamically allocate an array of pointers to rows for (int i = 0; i < height; i++) { // Allocate each row and set its columns to 0 grid[i] = new int[width]; fill_n(grid[i], width, 0); } return grid; } int main() { int** grid = MakeGridOfCounts(6, 6); // Get a 6x6 grid (initialized with 0s) // Do something with the grid... // Release allocated memory for (int i = 0; i < 6; i++) { delete[] grid[i]; } delete[] grid; return 0; }
In this solution, we use memory management techniques to dynamically allocate the 2D array, ensuring proper memory handling. The fill_n function is employed to initialize each element of the array to 0. Note that the allocation and deallocation of memory should be performed in the same scope (in this case, within the main function).
The above is the detailed content of How Can I Correctly Return a 2D Array from a C Function?. For more information, please follow other related articles on the PHP Chinese website!