I am trying to access the values pointed by pointers in a 2D array of double pointers, passed as a function arguments
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;
}
I have tried several variants but none of them works. This variant seems to me the most correct but doesn't work and I don't understand why. Any hint or explanation would be highly appreciated.
I know that having outdatav[i][j] = indatav[i][j]; with a return type of float** could work but this is not what I am looking for, because in this case the function would return the memory adress of the double pointers, while I am looking for the values of the variables pointed by those pointers.
A reproducible example would be:
#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;
}
Where ywould be have the values {{1.,2.},{3,4}}. // Note changes
cfun. And what do you mean by "none of them works"? Do you get build errors? Wrong results when running? Crashes? Something else? Please take some time to refresh how to ask good questions, as well as this question checklist.