Home > Backend Development > C++ > How to Safely Return and Manage a 2D Array from a C Function?

How to Safely Return and Manage a 2D Array from a C Function?

Linda Hamilton
Release: 2024-12-26 17:59:10
Original
694 people have browsed it

How to Safely Return and Manage a 2D Array from a C   Function?

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;
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template