【发布时间】:2019-12-19 05:39:14
【问题描述】:
我想用 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;
}
}
【问题讨论】:
-
这是未定义的行为,您可以越界访问该行(这就是
mat2,又名。&mat2[0]得到您)
标签: c++ function multidimensional-array