matrix_* matrix_insert_values(int n; double a[][n], int m, int n)
{
matrix_* x = matrix_new(m, n);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
x->v[i][j] = a[i][j];
return x;
}
我的测试矩阵示例
double in[][3] = {
{ 12, -51, 4},
{ 6, 167, -68},
{ -4, 24, -41},
{ -1, 1, 0},
{ 2, 0, 3},
};
我有点迷失,我无法弄清楚我的参数声明中的int n;
是什么,它适用于C但C ++不允许这种实现。我想了解这是如何工作的,因为我要将此代码迁移到C ++。
答案 0 :(得分:41)
它是C99 GNU扩展(GCC documentation)中很少使用的特性,用于转发声明VLA声明符中使用的参数。
matrix_* matrix_insert_values(int n; double a[][n], int m, int n);
您是否看到int n
两次出现的情况?第一个int n;
只是实际int n
的前向声明,它在最后。它必须出现在double a[][n]
之前,因为在n
的声明中使用a
。如果您可以重新排列参数,则可以在n
之前添加a
,然后您就不需要此功能了
matrix_* matrix_insert_values_rearranged(int m, int n, double a[][n]);
要清楚,GNU扩展只是函数参数的前向声明。以下原型是标准C:
// standard C, but invalid C++
matrix_* matrix_insert_values_2(int m, int n, double a[][n]);
您无法从C ++调用此函数,因为此代码使用C ++中不支持的可变长度数组。您必须重写该函数才能从C ++中调用它。
答案 1 :(得分:2)
如果这是你总是从C调用它的方式(即在编译时修复n和m),那么在C ++中你可以这样做:
template <int N, int M>
void matrix_insert_values(const double (&a)[M][N]);
int main() {
double in[5][3] = {
{ 12, -51, 4},
{ 6, 167, -68},
{ -4, 24, -41},
{ -1, 1, 0},
{ 2, 0, 3},
};
matrix_insert_values(in);
};
以N和M为模板参数,这些是在编译时从传递给函数的输入中自动推导出来的。