0

Hi everyone I got a trouble with the returning element of a function. I need to return a double pointer to pointer "double**". But I got a double[][] matrix.

Here is the code:

double** createPalette(int r, int g, int b) {
double incR = 1 / r, incG = 1 / g, incB = 1 / b;
double Cp[r * g * b][3];

for (int i = 0; i < r; i++) {
    for (int j = 0; j < g; j++) {
        for (int k = 0; k < b; k++) {
            Cp[i * r + j * g + k][0] = incR * i;
            Cp[i * r + j * g + k][1] = incG * j;
            Cp[i * r + j * g + k][2] = incB * k;
        }
    }
}

return Cp; //return &cp... (?)

}

I was looking for on internet, but I only found about simple pointer, no pointer to pointers.What should I do? Thanks for all.

Bardo91
  • 585
  • 2
  • 7
  • 17
  • 2
    Can't you really avoid returning `double**`? It's a lot less pain to return something else. (And would you please [stop stealing hotel room keys](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794)?). – R. Martinho Fernandes Jul 25 '13 at 11:37
  • That can't directly work, because `double**` and `double[][]` have different memory layout. You'll have to manually allocated the rows you need. Besides, returning a pointer to a stack-allocated variable is asking for trouble ! – Nbr44 Jul 25 '13 at 11:38
  • So, can I return the pointer if first I allocate with malloc the matrix? – Bardo91 Jul 25 '13 at 11:55
  • 1
    Why not return a `std::vector>` instead? (`double Cp[r * g * b][3]` is not even standard C++, it's a GCC extension variable-length-array. you will have a hard time returning it.) Unrelated: `incR`, `incG` and `incB` are all zero thanks to integer division. – Casey Jul 25 '13 at 12:00
  • Oh! Thks Casey! I didn't realize the integer division! – Bardo91 Jul 25 '13 at 19:26

1 Answers1

2

I think you know the value of r,g,b,so you can get the size of the matrix,you can do like this

void createPalette(int r, int g, int b, double matrix[][3])
minicaptain
  • 1,196
  • 9
  • 16