Reputation: 51
I know that you can pass arrays in other ways such as:
returnType functionName (dataType array[][10])
But I am interested in case where you don't know the size of the array in advance. I want to be able to pass the number of rows and number of columns as parameters.
How do i pass an array of any size to a C++ function? I want to do something along the lines of :
void functionName(dataType array[][], int num_rows, int num_cols){
// ***Some operation such as printing the array's contents***
}
Upvotes: 1
Views: 2232
Reputation: 1934
There are three ways to go about this:
template <std::size_t W, std::size_t H> void func(Type (&array)[W][H]) {}
Upvotes: 4
Reputation: 8215
Two possibilities:
Use a vector of vectors, then you won't even have to pass the sizes as extra arguments:
void functionName( std::vector<std::vector<dataType>>);
Use a one-dimensional array that emulates a two-dimensional one:
void functionName( dataType [] array, int num_rows, int num_cols);
Calculate the index of the one-dimensional array like this:
int i = row_index * num_cols + column_index;
Upvotes: 1