Search code examples
carraysdynamic-allocation

Passing a "normal" 2d array to function as **


I want to do this but it doesn't work. Is it possible to do it or do I have to declare A as double pointer float**? Note that I need an universal function for various array dimensions so I can't change the function arguments.

void func(float** arr, int x, int y){
    //access to arr[0][0] for e.g. causes SEGFAULT
}
...
float A[2][2]={{1,0},{0,1}};
func(A, 2, 2);

Solution

  • To pass 2D array to function you need to know at least element count in 2nd dimension at compilation time.

    void func(float arr[][2], int n)
    

    If you don't know the size of array at compile time there isn't much you can do except:

    void func(float *arr, int n, int m)
    {
        // getting arr[i][j] with arr[i*m + j]
    }
    
    float A[2][2]={{1,0},{0,1}};
    func(&A[0][0], 2, 2);