1

I am trying to declare, within my header file, a function that returns a 2D array. How can this be accomplished, given that we already know the size of the array? Below is what I'm currently doing.

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

5 Answers 5

7

I think you should use a typedef.

    typedef char TArray[2][2];
    TArray& getArr();
Sign up to request clarification or add additional context in comments.

Comments

5

Arrays are not first-class citizens in C++. Please use boost::array (or std::array in C++0x) instead. It will behave much more like you want it to behave.

Comments

4

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

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

or

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

Hope this helps.

1 Comment

Use a typedef.
-1

Yup, a pointer to a pointer is the way to go. It's really hard to think about. I recommend you do a memory map on a piece of paper just to understand the concept. When I was taking C++ classes I decided I wanted functionality just like you are suggesting, after a lot of time, I drew a map of all the memory I needed and it dawned on me I was looking at a pointer to a pointer. That blew me away.

1 Comment

While it may make the most sense to return the array data member given, this question is vaguely worded: all these downvotes are unwarranted. This is still good advice in general, even if I disagree with emphasis on manual memory management.
-2

It turns-out my original answer was totally incorrect, but I can't delete it since it's been accepted. From 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 had compiled my original solution only with the OP's given class declaration, not the definition of getArr().)

Just return a pointer to a pointer.

char** getArr();

1 Comment

@Fred and @Johannes Ugh, thanks for pointing that out. I've corrected the answer and converted it to community wiki.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.