Xemerau
Xemerau

Reputation: 13

Passing a multidimensional array between classes

I know that you can pass a multidimensional array into a function using:

void Class1::foo(Bar bars[][10])
{
   // Do stuff
}

and that you could return a pointer to the first member in a single-dimensional array by using:

Bar* Clas2::getBars()
{
   return bars;  //Where bars is a member of a class
}

However when 'bars' is a multidimensional array, I get the error:

Cannot convert Bar (*)[10] to Bar* in return

Could someone clarify why this is occuring?

Upvotes: 0

Views: 104

Answers (2)

HolyBlackCat
HolyBlackCat

Reputation: 96941

You should use:

Bar (*Clas2::getBars())[10]
{
    return bars;  //Where bars is a member of a class
}

or better looking way:

typedef Bar (*Bar10x10ptr)[10];

Bar10x10ptr Clas2::getBars()
{
    return bars;  //Where bars is a member of a class
}

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

You should write as the compiler says

Bar (*)[10] Clas2::getBars()
{
   return bars;  //Where bars is a member of a class
}

You said correctly that "you could return a pointer to the first member in a .. array". The member or more precisely element of your two dimensional array is one dimensional array of type Bar [10]. The pointer to this element will look as Bar (*)[10]

Oh I am sorry indeed shall be as

Bar (* Clas2::getBars() )[10]
{
   return bars;  //Where bars is a member of a class
}

Or you can use typedef. For example

typedef Bar ( *BarPtr )[10];
BarPtr Clas2::getBars()
{
   return bars;  //Where bars is a member of a class
}

Upvotes: 1

Related Questions