Home >Backend Development >C++ >How to Return a 2D Array in C Using Pointers?
How to Return a 2D Array Using Arrays
Instead of directly returning the 2D array using its name, as in the given code, you can create and return a pointer to the array. The following code snippet demonstrates how to accomplish this:
int** create2DArray(int rows, int cols) { int** array = new int*[rows]; // Allocate row pointers for (int i = 0; i < rows; i++) { array[i] = new int[cols]; // Allocate columns for each row } return array; }
By using a pointer to the array, you can return the 2D array without violating the language rules and ensure that the array is properly deallocated when it is no longer needed.
The above is the detailed content of How to Return a 2D Array in C Using Pointers?. For more information, please follow other related articles on the PHP Chinese website!