将表示二维数组的指针传递给 C++ 中的函数 [英] Passing a pointer representing a 2D array to a function in C++
问题描述
根据这个网站,我应该可以使用以下代码:
According to this site, I should be able to use the following code:
double stuff[3][3];
double **p_stuff;
p_stuff = stuff;
但我收到投诉,说分配不允许转换.
But I get a complaint that the conversion is not allowed by assignment.
我做错了吗?
我有一个 extern "C" 类型的函数,我想将它传递给 double [3][3].所以我想我需要让它成为一个指针,对吗?
I have an extern "C" type function that I want to pass this double stuff[3][3] to. So I think i need to make it a pointer, right?
推荐答案
关于将此 double stuff[3][3]
传递给 C 函数,您可以
Regarding the edit: to pass this double stuff[3][3]
to a C function, you could
1) 传递一个指向整个二维数组的指针:
1) pass a pointer to the whole 2D array:
void dostuff(double (*a)[3][3])
{
// access them as (*a)[0][0] .. (*a)[2][2]
}
int main()
{
double stuff[3][3];
double (*p_stuff)[3][3] = &stuff;
dostuff(p_stuff);
}
2) 传递指向第一个一维数组(第一行)和行数的指针
2) pass a pointer to the first 1D array (first row) and the number of rows
void dostuff(double a[][3], int rows)
{
// access them as a[0][0] .. a[2][2]
}
int main()
{
double stuff[3][3];
double (*p_stuff)[3] = stuff;
dostuff(p_stuff, 3);
}
3) 传递一个指向第一行第一个值的指针以及列数和行数
3) pass a pointer to the first value in the first row and the number of both columns and rows
void dostuff(double a[], int rows, int cols)
{
// access them as a[0] .. a[8];
}
int main()
{
double stuff[3][3];
double *p_stuff = stuff[0];
dostuff(p_stuff, 3, 3);
}
(最后一个选项并不严格符合标准,因为它将指向一维数组(第一行)元素的指针提前到该数组的末尾)
(that this last option is not strictly standards-compliant since it advances a pointer to an element of a 1D array (the first row) past the end of that array)
如果这不是 C 函数,还有更多选择!
If that wasn't a C function, there'd be a few more options!
这篇关于将表示二维数组的指针传递给 C++ 中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!