How to return a 2-dimensional array in C ++

I have a segmentationfault in the line: cout <<b [0] [0];

Can anyone tell me what should I do to fix my code?

#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;
}
+3
source share
5 answers

A 2-dimensional array is not the same as an array of pointers, which is interpreted as int**. 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];
}
+5
source

Being C ++ rather than c, there are better ways to process arrays of all kinds and transfer them.

+3
source

tab int **. int (*)[2]. [] , 0, NULL. :

#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;
}
+2

seg , "int *". 2D- ...

"x * y" ... , , :)

+1

a 2 diminsional array - , . 2- - , , 2-

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

, . , 2- . , , , , ?

edit: * 2 [0 + (sizeof (int) * 2) * 0]. : . 2 int. sizeof (int) .

0

Source: https://habr.com/ru/post/1726194/


All Articles