开发者

How to return 2 dimension array in C++

I have a segmentationfault at the line :

cout <<  b[0][0];

Could someone tell me what should I do to fix my code?

#include <iostream>
using namespace std;

int** getta开发者_Go百科b(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;
}


A 2-dimensional array is not the same thing as an array of pointers, which is how int** is interpreted. Change the return type of 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}
}

Or:

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];
}


Being c++, rather than c, there are much better ways of handling arrays of all sorts, and passing them around.


The type of tab without square brackets is not actually int **. It is actually int (*)[2]. When you apply two [] operators to the resulting pointer, you end up dereferencing the first value in your array, 0, as a NULL pointer. Try this instead:

#include <iostream>
using namespace std;

typedef int (*foo)[2];

foo gettab(int tab[][2]){
   return tab;
}

int main() {
   int a[4][2] = {{0, 0}, {1, 0}, {2, 0}, {2, 1}};
   foo b = gettab(a);
   cout <<  b[0][0];
   return 0;
}


Your seg fault us because you pass in an "int*" effectively. A 2D array is not a double pointer ...

You are best off using a pointer that is "x*y" in size and addressing it without the 2 dimensions ... the code will end up the same anyway as the compiler will just generate the same code you would have to write more explicitly anyway :)


a 2 diminsional array isn't the same thing as an array of pointers. a 2 dimensional array is just a pointer to a hunk of memory that you have told the compiler to let you access as a 2 dimensional array

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 + 2*0];   
   return 0;
}

will do what you want. But I wonder if you really need to be trying to return a 2 dimensional array from a function in the first place. Perhaps a less made-up example if what you are trying to do would be helpful?

edit: fixed missing *2 in the calculation [0 + (sizeof(int)*2)*0]. edit again: well that was dumb. the multiplication of the column size of 2 by the size of an int is automatic in this case. sizeof(int) removed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜