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

How to Properly Return a 2D Array from a C Function?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 06:47:10945browse

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) { .... } 
  1. Create the 2D Array ( create2DArray() ):

    • First, we create a pointer to the 2D array and a pointer to each individual row.
    • We allocate memory for the rows and then for each row, we allocate memory for the columns.
int** array2D = new int*[height];
for (int h = 0; h < height; h++) {
   array2D[h] = new int[width];
   .
   .
   .
}
  1. Return the Array (create2DArray() ):

    • Once the array is created, the pointer to the first row (array2D) is returned. This pointer represents the entire array.
  2. Clean up Memory (main() ):

    • It's crucial to release the memory allocated for the 2D array once it is no longer needed. This involves deleting each row's memory and then the pointer to the first row to prevent memory leaks.
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!

Statement:
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