Declaring a function returning a 2D array to a header file?

I am trying to declare a function returning a 2D array in my header file. How can this be done, given that we already know the size of the array? The following is what I am doing now.

class Sample { public: char[x][y] getArr(); void blah(int x, int y); private: const static int x = 8; const static int y = 2; char arr[x][y]; }; 
+1
source share
5 answers

It turns out my original answer was completely wrong, but I can’t delete it from the moment it was accepted . Of the two separate answers below, I was able to compile this:

 class Sample { const static int x = 8; const static int y = 2; public: typedef char SampleArray[x][y]; SampleArray& getArr(); void blah(int x, int y); private: SampleArray arr; }; Sample::SampleArray& Sample::getArr () { return arr; } 

(I compiled my original solution only with the declaration of the OP class, and not with the definition of getArr() .)

Just return the pointer to the pointer.

 char** getArr(); 

-2
source

I think you should use typedef.

  typedef char TArray[2][2]; TArray& getArr(); 
+7
source

Arrays are not first-class citizens in C ++. Instead, use boost::array (or std::array in C ++ 0x). He will behave a lot more as you want him to behave.

+5
source

In C ++, the array itself cannot be returned directly from a function. In addition, you can return an array reference or an array pointer. So you can write like:

 char (&getArr())[x][y] { return arr; } 

or

 char (*getArr())[x][y] { return &arr; } 

Hope this helps.

+4
source

Yup, a pointer to a pointer is the way to go. It is very difficult to think. I recommend that you make a memory card on a piece of paper to understand the concept. When I accepted the C ++ classes, I decided that I would like functionality, as you suggest, after a lot of time I drew a map of all the memory I needed, and it became clear to me that I was looking at a pointer to a pointer. It let me go.

-1
source

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


All Articles