How can I pass a dynamic multidimensional array to a function?

后端 未结 9 2340
再見小時候
再見小時候 2020-12-19 05:48

How can I pass a multidimensional array to a function in C/C++ ?

The dimensions of array are not known at compile time

9条回答
  •  忘掉有多难
    2020-12-19 06:12

    Passing the array is easy, the hard part is accessing the array inside your function. As noted by some of the other answers, you can declare the parameter to the function as a pointer and also pass the number of elements for each dim of the array.

    #define xsize 20
    #define ysize 30
    int array[xsize][ysize];
    void fun(int* arr, int x, int y)
    {
     // to access element 5,20
     int x = arr[y*5+20];
    }
    
    fun(array, xsize, ysize);
    

    Of course, I've left out the whole business of allocating the array (since it isn't known what its size will be, you can't really use #defines (and some say they're bad anyhow)

提交回复
热议问题