将数组传递给函数(以及为什么在C ++中不起作用) [英] Passing array to a function (and why it does not work in C++)

查看:84
本文介绍了将数组传递给函数(以及为什么在C ++中不起作用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些可以编译的C代码,但是我不明白为什么。具体来说,我有一个C库,其中使用这种格式的代码很多:

I have come across some C code that compiles, but I do not understand why. Specifically, I have a C library that has a lot of code using this format:

void get_xu_col(int i_start,
                int n,
                double x[n],
                int n_x,
                int n_u,
                int n_col,
                double xu_col[n_col][n_x + n_u]){
    ... 
}

int main(){
    ...
    double xu_col[n_col][n_x + n_u];
    get_xu_col( ..., xu_col );
    ...
}

我不明白的是为什么编译器允许在数组中调整大小。据我所知,大小必须固定(例如 xu_col [9] [7] )或不确定(例如 xu_col [] [ ] )。在上面的代码中,似乎大小不是编译时常量。

What I don't understand is why the compiler allows for sizing in the arrays. To the best of my understanding, either the sizes must be fixed (e.g. xu_col[9][7]) or undefined (e.g. xu_col[][]). In the above code, it appears that the sizes are not compile-time constants.

编译器是否只是忽略此处的参数?还是真的在尺寸上进行编译时检查?

Is the compiler just ignoring the arguments here? or is it really doing a compile-time check on the dimensions?

如果是后者,则单独传递尺寸似乎容易出错。

If it is the latter, then it seems error-prone to pass the dimensions separately.

问题的第二部分是:

为什么同一版本在C ++中不起作用?当我将文件扩展名从 .c 更改为 .cpp 并尝试重新编译时,我得到

Why doesn't the same version work in C++? When I literally change the file extension from .c to .cpp and try to recompile, I get

candidate function not viable: no known conversion from 'double [n_col][n_x + n_u]' to 'double (*)[n_x + n_u]' for 7th argument
void get_xu_col(int i_start, int n, double x[n], int n_x, int n_u, int n_col, double xu_col[n_col][n_x + n_u]);

我想知道我应该使用哪种惯用法将这段代码转换为C ++,因为显然习惯用语在C语言中有效,但在C ++中不起作用。

I would like to know which idiom I should use to convert this code to C++, since apparently the previous idiom was something that works in C, but not C++.

推荐答案

在C语言中,可以使用函数参数来定义可变长度数组参数的大小,只要该大小在参数列表中的数组之前。 C ++不支持。

In C, it is possible to use function parameters to define the size of a variable length array parameter as long as the size comes before the array in the parameter list. This is not supported in C++.

这篇关于将数组传递给函数(以及为什么在C ++中不起作用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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