Returning a 2D Array from a Function in C
When working with 2D arrays in C , the approach presented in the code provided is not recommended. Instead, consider implementing the following function:
int** create2DArray(unsigned height, unsigned width) { int** array2D = 0; array2D = new int*[height]; for (int h = 0; h < height; h++) { array2D[h] = new int[width]; for (int w = 0; w < width; w++) { // Initialize array elements as needed } } return array2D; }
This function takes the height and width of the desired 2D array as unsigned integers and dynamically allocates memory for it. The outer array is allocated first, and then the inner arrays are allocated within the loop.
Remember to deallocate the memory after usage to prevent memory leaks. This can be done by looping through the elements and deleting both the inner and outer arrays.
Example Usage:
int height = 15; int width = 10; int** my2DArray = create2DArray(height, width); // Use the array as needed // ... for (int h = 0; h < height; h++) { delete [] my2DArray[h]; } delete [] my2DArray; my2DArray = 0; // Set pointer to null to prevent dangling pointer
The above is the detailed content of How to Safely Return and Manage a 2D Array from a C Function?. For more information, please follow other related articles on the PHP Chinese website!