简体   繁体   English

在C ++中将静态数组声明为指针

[英]declare a static array as pointer in c++

Here are a few lines of C++ code I recently saw. 这是我最近看到的几行C ++代码。

double a[p][p];
for(i=0;i<p;i++)
{
    for(j=0;j<p;j++)
    {
        a[i][j] = m[i][j]; //m is sth we are given.
    }
}
dgeev_(&jobvl,&jobvr,&p,(double*)a,&lda,(double*)wr,(double*)wi,(double*)vl,
      &ldvl,(double*)vr,&ldvr,(double*)work,&lwork,&info);
// sth else..

dgeev_ is a function and you can find its documentation here: http://www.netlib.org/clapack/old/double/dgeev.c dgeev_是一个函数,您可以在这里找到其文档: http : //www.netlib.org/clapack/old/double/dgeev.c

dgeev_ is declared in header in the following way, so we can use C function in C++ codes. dgeev_是通过以下方式在标头中声明的,因此我们可以在C ++代码中使用C函数。

extern "C" {
void dgeev_(char*, char*, int*, double*, int*, double*, double*, double*,
 int*, double*, int*, double*, int*, int*);
}

As we can see, a is static array, and dgeev_ need a variable of type doublereal * for the 4th parameter. 如我们所见, a是静态数组, dgeev_需要第四个参数的类型为doublereal *的变量。

What does (double*)a do here? (double*)a在这里做什么?

It's either a mistake or the author is playing a trick on you. 这是一个错误,或者是作者在骗你。

He's used a C-style cast to "hack" the value a into the double* type, so that a two-dimensional array may be treated as a single-dimensional array. 他使用的C样式转换到“黑客”的值adouble*类型,从而使二维数组可以作为一维数组处理。 ( doublereal is just an alias for double .) doublereal只是double的别名 。)

Problem is, a isn't a double* , nor is it actually convertible to a double* . 问题是, a 不是 double* ,也不是实际上可以转换为double* I don't know what it is convertible to, since VLAs are only available in C++ as a GCC extension; 我不知道它可以转换成什么,因为VLA仅在C ++中作为GCC扩展提供; there is no standard wording to consult. 没有标准的措辞可以参考。 I'm going to just conclude that this program has undefined behaviour (though it probably appears to work, due to how these things are practically laid out in memory). 我将仅得出结论,该程序具有未定义的行为(尽管由于这些内容实际上是在内存中布置的,所以它似乎可以工作)。

If the author wants to be able to safely read this array using single-dimension indices, he should have declared it that way to begin with (optionally providing the illusion of 2D indexes on top of the data store). 如果作者希望能够使用一维索引安全地读取此数组,那么他应该以这种方式声明它(可以选择在数据存储顶部提供2D索引的错觉 )。

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

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