how to pass 2 dimensional array if both dimensions are unknown at compile time

后端 未结 5 1669
[愿得一人]
[愿得一人] 2021-01-20 16:26

what is this the correct way to pass 2 dimensional array of unknown size?

reprVectorsTree::reprVectorsTree(float tree[][], int noOfVectors, int dimensions)
<         


        
5条回答
  •  自闭症患者
    2021-01-20 16:37

    In modern C, starting from C99, it is a simple as that

    void foo(size_t n, size_t m, double A[n][m]) {
      //
    }
    

    and here you go. The only thing that you'd have to have in mind is that the sizes must come before the array in the argument list.

    To avoid to allocate such a beast on the stack on the calling side you should just do

    double (*A)[m] = malloc(sizeof(double[n][m]));
    

    such a "matrix" can be used as you are used to with something like A[i][j] and a call to foo would just look like

    foo(n, m, A);
    

提交回复
热议问题