无法将(*)[]转换为** [英] Cannot convert (*)[] to **

查看:180
本文介绍了无法将(*)[]转换为**的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建了一个文件:

If I create a file:

test.cpp:

void f(double **a) {

}

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

然后运行:
g ++ test.cpp -o test

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

我得到

test.cpp: In function `int main()':
test.cpp:8: error: cannot convert `double (*)[2]' to `double**' for argument `1'
 to `void f(double**)'

为什么我不能这样做?

Why is that I can't do this?

不是double var [4] [2]与执行double ** var然后分配内存是一样的

Isn't double var[4][2] is the same as doing double **var and then allocating the memory?

推荐答案

http://stackoverflow.com/questions/ 308279 / c-vs#308724

请参阅 Excursion:Multi Dimensional Arrays ,介绍如何将多维数组传递到函数作为参数。基本上你想把你的代码改成:

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);
}

调用函数必须知道最后一个维。否则索引数组,编译器将无法计算到值到数组的正确距离(a [1] sizeof(double [2]) a [0])。

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);
}

编译器将为每个值N与函数一起使用,自动推导出正确的N。

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

这篇关于无法将(*)[]转换为**的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆