Home >Backend Development >C++ >How to Properly Return a 2D Array from a C Function?
Returns 2D arrays in C
Returining a 2D array from a function in C can be a tricky task. One approach, as demonstrated by the provided code, attempts to return a 2D array using the code shown below but this approach is not suitable.
int **MakeGridOfCounts() { int cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }}; return cGrid; }
Instead, a viable approach involves creating and returning a pointer to the 2D array using dynamic memory allocation. Let's explore how this is done with an improved code example:
#include <cstdio> int** create2DArray(unsigned height, unsigned width) { .... }
Create the 2D Array ( create2DArray() ):
int** array2D = new int*[height]; for (int h = 0; h < height; h++) { array2D[h] = new int[width]; . . . }
Return the Array (create2DArray() ):
Clean up Memory (main() ):
for (int h = 0; h < height; h++) { delete [] array2D[h]; } delete [] array2D;
This approach ensures proper memory management and provides a way to return a 2D array from a function in C .
The above is the detailed content of How to Properly Return a 2D Array from a C Function?. For more information, please follow other related articles on the PHP Chinese website!