tepsijash
tepsijash

Reputation: 400

Returning a pointer to array of fixed sized arrays C++

I tried searching everywhere, but because it is such a perplexing question, I wasn't able to find what I was looking for. I am trying to create function/method but I don't know how to specify its return type, which should be:

double(*)[3]

I want to be able to use a query like this one:

double R[3][3];
query ( &output, R );

but instead of R[3][3], I have a vector std::vector<double> R_vect (9); and I do this:

query ( &output, reinterpret_cast<double(*)[3]> (R_vect.data()) );

which is a mess, so I wanted to implement a function to make it readable, say:

ReturnType Cast ( const std::vector<double>& R_vect ) {
  return reinterpret_cast<double(*)[3]> (R_vect.data());
}

but I can't specify the return type. I used typedef, and it works:

typedef double DesiredCast[3];
DesiredCast* Cast ( ... ) { ... }

but I am still curious how to do it without typedefs.

Upvotes: 4

Views: 1756

Answers (2)

user1084944
user1084944

Reputation:

You should always typedef complicated return types like these, rather than require the reader to untangle them. (or redesign so you don't have complicated types!)

But you can just follow the pattern. To declare a variable of this type you would do

double (*var)[3];

and to make it a function you just put the usual decoration in the usual place next to the name, despite horrible it seems. e.g. with an int argument named z:

double (*func(int z))[3]
{
    // ...
}

Incidentally, cdecl will do that for you, once you learn its language.

Upvotes: 4

jschultz410
jschultz410

Reputation: 2899

It's pretty bizarre syntax:

double (*foo(void))[3]
{
  static double f[3][3];

  return f;
}

Upvotes: 0

Related Questions