我在该行有一个段错误:
cout << b[0][0];
有人可以告诉我应该如何修复我的代码吗?
#include <iostream>
using namespace std;
int** gettab(int tab[][2]){
return (int**)tab;
}
int main() {
int a[4][2] = {{0, 0}, {1, 0}, {2, 0}, {2, 1}};
int ** b = gettab(a);
cout << b[0][0];
return 0;
}
最佳答案
二维数组与指针数组不同,后者是 int**
的解释方式。更改 gettab 的返回类型。
int* gettab(int tab[][2]){
return &tab[0][0];
}
int main() {
int a[4][2] = {{0, 0}, {1, 0}, {2, 0}, {2, 1}};
int* b = gettab(a);
cout << b[0]; // b[row_index * num_cols + col_index]
cout << b[1 * 2 + 0]; // the 1 from {1, 0}
}
或者:
int (*gettab(int tab[][2]))[2] {
return tab;
}
// or:
template<class T> struct identity { typedef T type; };
identity<int(*)[2]>::type gettab(int tab[][2]) {
return tab;
}
int main() {
int a[4][2] = {{0, 0}, {1, 0}, {2, 0}, {2, 1}};
int (*b)[2] = gettab(a);
cout << b[0][0];
}
关于c++ - 如何在 C++ 中返回二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1937181/