Cannot convert (*)[] to **

后端 未结 2 653
走了就别回头了
走了就别回头了 2021-02-04 16:56

If I create a file:

test.cpp:

void f(double **a) {

}

int main() {
    double var[4][2];
    f(var);
}

And then run: g++ test.cpp -o t

相关标签:
2条回答
  • 2021-02-04 17:15

    C++ strings: [] vs. *

    Look at the Excursion: Multi Dimensional Arrays which describes how you pass multi dimensional arrays to functions as arguments. Basicially you want to change your code into this:

    // same as void f(double (*a)[2]) {
    void f(double a[][2]) { 
    
    }
    
    int main() {
        // note. this is not a pointer to a pointer, 
        // but an array of arrays (4 arrays of type double[2])
        double var[4][2];
    
        // trying to pass it by value will pass a pointer to its
        // first element 
        f(var);
    }
    

    All but the last dimensions have to be known to the called function. Otherwise indexing the array, the compiler would not be able to calculate the correct distance to values into your array (a[1] is sizeof(double[2]) bytes away from a[0]).

    You seem to want to be able to accept the array without knowing the size of the dimensions. You can use templates for this:

    template<std::size_t N>
    void f(double a[][N]) { 
        // N == 2 for us
    }
    
    int main() {
        double var[4][2];
        f(var);
    }
    

    The compiler will make a copy of (instantiate) that template for each value of N used with the function, auto-deducing the right N.

    0 讨论(0)
  • 2021-02-04 17:16

    The problem is that a double** is a pointer to a pointer. Your 'f' function wants to be passed the address of a pointer to a double. If you call f(var), well, where exactly do you think that pointer is? It doesn't exist.

    This will work:

    double *tmp = (double *) var;
    f (&tmp);
    

    Also, it would work to change the definition of f:

    void f (double a[4][2]) { }
    

    Now f takes a pointer to the kind of array you have. That will work.

    0 讨论(0)
提交回复
热议问题