如何在C++中返回二维数组

use*_*642 4 c++

我在这一行有一个分段错误:cout << b [0] [0];

有人可以告诉我应该怎么做才能修复我的代码?

cout <<  b[0][0];
Run Code Online (Sandbox Code Playgroud)

小智 6

二维数组与指针数组不同,这是如何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}
}
Run Code Online (Sandbox Code Playgroud)

要么:

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];
}
Run Code Online (Sandbox Code Playgroud)