Giggs
Giggs

Reputation: 51

Passing Arrays of any size to C++ functions

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

Answers (2)

Vaibhav Bajaj
Vaibhav Bajaj

Reputation: 1934

There are three ways to go about this:

  1. You pass pointer to the first element with row and column size as the parameters.
  2. If array size is known at compile-time, you can use templates. Something like:

template <std::size_t W, std::size_t H> void func(Type (&array)[W][H]) {}

  1. You use a 2D vector and pass it into the function. But it's not so efficient if you don't need to resize separate columns.

Upvotes: 4

Frank Puffer
Frank Puffer

Reputation: 8215

Two possibilities:

  1. 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>>);

  2. 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

Related Questions