简体   繁体   English

返回指向固定大小数组的数组的指针C ++

[英]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); 但是我有一个向量std::vector<double> R_vect (9);来代替R[3][3] 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,它可以工作:

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

but I am still curious how to do it without typedefs. 但是我仍然很好奇没有typedef时该怎么做。

You should always typedef complicated return types like these, rather than require the reader to untangle them. 您应该始终对此类复杂的返回类型进行typedef定义,而不是要求读者解开它们。 (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. 要使其发挥作用,您只需将常用装饰放在名称旁边的常用位置即可,尽管看起来很恐怖。 eg with an int argument named z : 例如,带有一个名为zint参数:

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

Incidentally, cdecl will do that for you, once you learn its language. 顺便说一句,一旦您学习了cdecl的语言,它将为您做到这一点。

It's pretty bizarre syntax: 这是非常奇怪的语法:

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

  return f;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM