Home >Backend Development >C++ >How to Return a 2D Array in C Using Pointers?

How to Return a 2D Array in C Using Pointers?

Linda Hamilton
Linda HamiltonOriginal
2024-12-13 08:05:10840browse

How to Return a 2D Array in C   Using Pointers?

How to Return a 2D Array Using Arrays

Instead of directly returning the 2D array using its name, as in the given code, you can create and return a pointer to the array. The following code snippet demonstrates how to accomplish this:

int** create2DArray(int rows, int cols) {
  int** array = new int*[rows];  // Allocate row pointers
  for (int i = 0; i < rows; i++) {
    array[i] = new int[cols];  // Allocate columns for each row
  }
  return array;
}

By using a pointer to the array, you can return the 2D array without violating the language rules and ensure that the array is properly deallocated when it is no longer needed.

The above is the detailed content of How to Return a 2D Array in C Using Pointers?. 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