二维 C 样式数组的常见问题。该程序可以编译,但在调用 Print()
函数时崩溃:
#include <iostream>
using namespace std;
static const int sx = 5, sy = 3;
static double M[sy][sx] = { { 0.0, 1.0, 2.0, 3.0, 4.0 },
{ 0.1, 1.1, 2.1, 3.1, 4.1 },
{ 0.2, 1.2, 2.2, 3.2, 4.2 } };
void Print(double **M, int j, int i)
{
cerr << M[j][i] << endl;
}
int main()
{
cerr << M[2][3] << endl; // Prints 3.2
Print((double**)&M[0][0], 2, 3); // Crash
}
我的代码有什么问题?
是否可以在不更改 Print()
签名的情况下使其工作?
数组不是动态的。
最佳答案
这个:
static double M[sy][sx] = { { 0.0, 1.0, 2.0, 3.0, 4.0 },
{ 0.1, 1.1, 2.1, 3.1, 4.1 },
{ 0.2, 1.2, 2.2, 3.2, 4.2 } };
一点也不像double**
,将它或其中的任何东西强制转换成这样的类型是不正确的。如果您使用固定的数组数组(如果需要,可以将其称为二维数组),可以使用模板制作兼容的打印函数:
#include <iostream>
using namespace std;
static const int sx = 5, sy = 3;
static double M[sy][sx] = { { 0.0, 1.0, 2.0, 3.0, 4.0 },
{ 0.1, 1.1, 2.1, 3.1, 4.1 },
{ 0.2, 1.2, 2.2, 3.2, 4.2 } };
template<int M>
void Print( double(*ar)[M] , int j, int i )
{
std::cout << ar[j][i] << '\n';
}
int main()
{
Print(M, 2, 3);
return 0;
}
关于c++ - 二维 C 样式数组崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23828509/