0

Is there a way to pass 1D fixed array to 2D pointer functions. I can figure out passing 1D pointer arrays.

void prettyPrintMatrix_float(float **matrix, int rows, int cols){
    int i, j;

    for (i = 0; i<rows; i++){
        for (j = 0; j<cols; j++){
            printf("%10.3f", matrix[i][j]);
        }
        printf("\n");
    }
    return;
}

float myArray[10] = {0.0f};
float* myPointerArray = (float*)malloc(sizeof(float) * 10);
prettyPrintMatrix_float(&myPointerArray, 1, 10); // Works
prettyPrintMatrix_float(&myArray, 1, 10); // ERROR
prettyPrintMatrix_float(&(myArray[0]), 1 , 10); ERROR

So I can't think of a way to get around this. Only way I can think of is to create new function. Which I would rather not, if I don't have to.

user14492
  • 2,116
  • 3
  • 25
  • 44
  • `float* myPointerArray = myArray; prettyPrintMatrix_float(&myPointerArray, 1, 10);` ? – Eugene Sh. Oct 31 '17 at 14:30
  • @EugeneSh. I could kiss you right now. You sly dog. Write that as an answer if you want the sweet karma. – user14492 Oct 31 '17 at 14:50
  • Is there a reason why you can't use 2D arrays instead? https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays – Lundin Oct 31 '17 at 14:53
  • @Lundin Yes, because it won't help. I'll need to specifically create a new function that supports 2D array of fixed size. So the array would look like `float myArray[1][10];`, right? It still won't work. That's my another question: https://stackoverflow.com/questions/47037723/pass-fixed-sized-array-to-a-function-with-pointer-argument – user14492 Oct 31 '17 at 14:58
  • Just read the link I posted. – Lundin Oct 31 '17 at 15:04

1 Answers1

0

You can't do what you are trying to do, a float** is not a float* nor it has the same memory layout.

The first is a pointer to pointer to a float, which means that first dereference yields a pointer while with a float* you obtain directly the value.

You can take the address of a float* to obtain a float** but that's not what you want to do I guess (since rows will be trivially 1). A way to manage both 2D and 1D arrays in a single way is to always have a float* and use special functions to obtain the correct element for two dimensions, eg:

float get(float* data, float x, float y, float w) {
  return data[y*w + x];
}

so that everything can revolve around float*.

Jack
  • 131,802
  • 30
  • 241
  • 343