I am new to programming.
User will be enter the size of 2D array and then I want to pass this array to function. How can I do this?
I am new to programming.
User will be enter the size of 2D array and then I want to pass this array to function. How can I do this?
There are two ways to accomplish your goal.
The first way is using dynamically allocated C-style arrays. You shouldn't do this in C++ unless you are forced to support existing code. But in this case it is better to consider refactoring, maybe.
The second way is using std::vector
. This class encapsulates low-level manipulations with memory. It will free you from many potential bugs.
To show you advantages of std::vector
I have written two programs. They input sizes of 2D array (in another way, it is called a matrix) and create it.
Creating matrix using C-style arrays requests a lot of code and manipulations with pointers. For the sake of simplicity the following code doesn't handle exceptions. In real code you should do it to avoid memory leaks, but the code would become even harder.
#include <iostream>
#include <cstddef>
using namespace std;
void function(int** matrix, size_t nrows, size_t ncols)
{
}
int main()
{
size_t nrows;
size_t ncols;
cin >> nrows >> ncols;
// allocate memory for matrix
int** matrix = new int*[nrows];
for (size_t i = 0; i < nrows; ++i)
matrix[i] = new int[ncols];
function(matrix, nrows, ncols);
// release memory
for (size_t i = 0; i < nrows; ++i)
delete[] matrix[i];
delete[] matrix;
}
So in C++ it would be very easier using std::vector
. Since std::vector
is a class it has constructor and destructor encapsulating allocating and releasing memory.
#include <iostream>
#include <vector>
using namespace std;
void function(vector<vector<int>>& matrix)
{
}
int main()
{
size_t nrows;
size_t ncols;
cin >> nrows >> ncols;
// create matrix
vector<vector<int>> matrix(nrows);
for (size_t i = 0; i < nrows; ++i)
matrix[i] = vector<int>(ncols);
// you don't even need to pass sizes of matrix
function(matrix);
// automatically called destructor of matrix releases memory
}