C++函数中推广二维数组

C++ generalize two dimension array in function

本文关键字:二维数组 函数 C++      更新时间:2023-10-16

我想用C++编写一个函数,它接受任何大小的矩阵并打印出来。

我的代码如下,它可以工作。但我的问题:

1( 这是最佳实践吗? 2(为什么使用(int *)铸造有效,而static_cast<int *>则无效?

谢谢

#include <iostream>
using namespace std;
void print_matrix(int *, int, int);
int main()
{
int mat[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int mat2[5][5] = {{1, 2, 3, 40, 50},
{4, 5, 6, 70, 80},
{7, 8, 9, 10, 20},
{17, 18, 19, 10, 20},
{71, 81, 91, 110, 120}
};
print_matrix((int *)mat2, 5, 5);
cout << endl;
print_matrix((int *)(mat), 3, 3);
cout << endl;
//    static cast does not work:
//    error: invalid static_cast from type 'int [3][3]' to type 'int*'|
//    print_matrix(static_cast<int *>(mat), 3, 3);
return 0;
}
void print_matrix(int *matPtr, int row, int col)
{
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++)
cout << *(matPtr + col * i + j) << 't';
cout << endl;
}
}

这是最佳实践吗?

不,不是。

最好使用函数模板。

template <size_t NR, size_t NC>
void print_matrix(int (&matrix)[NR][NC])
{
...
}

并将其称为:

print_matrix(mat2); // NR and NC are deduced by the compiler

为什么使用(int *)进行铸造有效,而static_cast<int *>则无效?

鉴于

int mat[3][3] = { ... };

以下指针具有相同的数值,即使指针的类型不同。

int (*p1)[3][3] = &mat;
int (*p2)[3] = &mat[0];
int *p3 = &mat[0][0];

因为这种巧合,使用(int*)作品。

使用static_cast<int*>不起作用,因为当 2D 数组衰减到指针时,它不会衰减到int*-mat衰减到int (*)[3](指针指向"3ints 的数组"(,mat2衰减到int (*)[5](指针指向"5ints 的数组"(。它们不能投射到一般的int*