Home > Backend Development > C++ > How Can I Correctly Return a 2D Array from a C Function?

How Can I Correctly Return a 2D Array from a C Function?

DDD
Release: 2024-12-15 10:20:11
Original
676 people have browsed it

How Can I Correctly Return a 2D Array from a C   Function?

Implementing a Function to Return a 2D Array in C

The provided code snippet attempts to return a 2D array from a function, but it has an issue with the array declaration. To rectify this, we can introduce a more comprehensive solution:

#include <iostream>
using namespace std;

// Returns a pointer to a newly created 2D array with dimensions [height x width]
int** MakeGridOfCounts(int height, int width) {
  int** grid = new int*[height];  // Dynamically allocate an array of pointers to rows
  
  for (int i = 0; i < height; i++) {  // Allocate each row and set its columns to 0
    grid[i] = new int[width];
    fill_n(grid[i], width, 0);
  }
  
  return grid;
}

int main() {
  int** grid = MakeGridOfCounts(6, 6);  // Get a 6x6 grid (initialized with 0s)
  
  // Do something with the grid...

  // Release allocated memory
  for (int i = 0; i < 6; i++) {
    delete[] grid[i];
  }
  delete[] grid;
  
  return 0;
}
Copy after login

In this solution, we use memory management techniques to dynamically allocate the 2D array, ensuring proper memory handling. The fill_n function is employed to initialize each element of the array to 0. Note that the allocation and deallocation of memory should be performed in the same scope (in this case, within the main function).

The above is the detailed content of How Can I Correctly Return 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template