Tayab Soomro
Tayab Soomro

Reputation: 315

Passing 2D array as an argument to a function which takes 1D array

Might sound like a stupid question:

Is it possible to pass 2D array as an argument to a function which takes 1D array

For example:

I have an array players[4][5] and also a function bestCard(), the header for that function looks something like this void bestCard(int arr[5]) <- this 5 is referring to the second dimension of array players

I want to pass players[4][...] in the function bestCard() in a way that the only last dimension is considered to be as an array i.e players[5]

Not sure if my question is comprehensive.

Upvotes: 1

Views: 1241

Answers (2)

Kelvin Lee
Kelvin Lee

Reputation: 65

I am a beginner at C++, but as far as I know, it would not be possible to pass a 2-d array to your function bestCard(), assuming that you have not overloaded your bestCard() function to take different types of parameters.

Based on the information you have given to me in your question, I am guessing that there are 4 players, and each holds a hand of 5 cards.

If you want to pass bestCard() a single player's hand, you will have to write something like this:

bestCard(players[0]) // Determine the bestCard for the first player.
bestCard(players[1]) // Determine the bestCard for the second player.
...
bestCard(players[3]) // Determine the bestCard for the fourth player.

Even though players is in fact a 2-d array, each of the players[i] (for 0 < i < 4) evaluate to 1-dimensional arrays. Thus, bestCard() ought to be able to accept them as an argument.

Upvotes: 1

Peter
Peter

Reputation: 36597

A 2D array is an array of 1D arrays.

In your case, that means player[i] is an array of five elements, for i between 0 and 3. So passing player[i] to your function will pass an array of 5 elements (or more strictly, a pointer to the first element of an array of 5 elements).

Upvotes: 2

Related Questions