我正在尝试访问作为函数参数传递的二维双指针数组中的指针指向的值
float cfun (float **indatav, int rows, int cols)
{
float* *outdatav = new float*[rows];
for (int i=0; i < rows; i++){
outdatav[i] = new float[cols];
}
for (int i=0; i < rows; i++){
for (int j=0; j < cols; j++){
outdatav[i][j] = *(*(indatav[i])[j]);
}
}
return outdatav;
}
我尝试了几种变体,但没有一个有效。这个变体在我看来是最正确的,但不起作用,我不明白为什么。任何提示或解释将不胜感激。
我知道有outdatav[i][j] = indatav[i][j];
一个返回类型float**
可以工作,但这不是我要找的,因为在这种情况下,函数将返回双指针的内存地址,而我正在寻找那些指向的变量的值指针。
一个可重现的例子是:
#include <iostream>
#include <vector>
using namespace std;
//float cfun (float **indatav, int rows, int cols)
float** cfun (float **indatav, int rows, int cols)
{
float** outdatav = new float*[rows];
for (int i=0; i < rows; i++){
outdatav[i] = new float[cols];
}
for (int i=0; i < rows; i++){
for (int j=0; j < cols; j++){
outdatav[i][j] = *(*(indatav[i])[j]);
}
}
return outdatav;
}
int main(){
// float indatav[2][2] = {{1.,2.};{3;4}} // WRONG!
float indatav[2][2] = {{1.,2.},{3,4}};// RIGHT!
int rows = 2, cols = 2;
// float y[2][2] = cfun(**indatav, rows, cols); // Try compiling this!
float **y = cfun(indatav, rows, cols); // THIS DOES WHAT YOU ARE AKSING!
return 0;
}
哪里y
会有值{{1.,2.},{3,4}}
。// 注意变化
当您正确地取消引用outdatav
二维数组时,您似乎很舒服,那么是什么让您认为indatav
二维数组应该有任何不同的对待?尝试以下两行校正:
float** cfun (float **indatav, int rows, int cols) // Now return 2D pointer!
{
float* *outdatav = new float*[rows];
for (int i=0; i < rows; i++){
outdatav[i] = new float[cols];
}
for (int i=0; i < rows; i++){
for (int j=0; j < cols; j++){
// outdatav[i][j] = *(*(indatav[i])[j]);
outdatav[i][j] = indatav[i][j]; // Why don't you think this will work?
}
}
return outdatav; // Note change in function declaration!
}
毕竟,两者outdatav
和indatav
具有完全相同的声明——两者都是float**
.
在您编辑的问题中,您现在有一个电话:y = cfun(**indatav, rows, cols);
然后添加
其中 y 的值为 {{1.,2.},{3;4}}
这正是我如何解释你想要的。您需要将变量“y”声明为:float** y
并且第 0 行和第 1 列的数据的实际值将由表达式给出y[0][1]
。但是,您的调用cfun
错误并且应该是:y = cfun(indatav, rows, cols);
对于您给出的示例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句