0

I want to write a function that returns pointer to two-dimensional array of pointers. I have this array: Organism* worldTab[20][20]; and my friend advised to write the function I want in this way:

    Organism** getWorldTab() {
    return worldTab[20];
}

Is it correct? When I want to do this (temp is Organism*** temp;):

    *temp = world.getWorldTab();

Visual Studio throws an exception

    Exception thrown: write access violation.

    this->temp was 0xCCCCCCCC.

and I am pretty sure getWorldTab()functions is a problem.

worldTab definition: Organism* worldTab[20][20];

14
  • 5
    worldTab[20] is out of bounds. Commented Apr 21, 2017 at 18:11
  • 1
    You need to give more context. Where is worldTab defined? Commented Apr 21, 2017 at 18:11
  • 2
    Please read stackoverflow.com/help/mcve and Edit your question Commented Apr 21, 2017 at 18:14
  • 4
    Organism*** -- three stars is a sure sign of trouble. Commented Apr 21, 2017 at 18:14
  • 2
    It depends on a lot of things, for example the storage class of worldTab. But it's a bad idea in any case. Use std::vector instead of this horrible low-level pointer management. Commented Apr 21, 2017 at 18:15

1 Answer 1

1

An array is not a pointer, although it can be converted into a pointer to its first element in some situations, and a pointer to an array is completely unlike a pointer to a pointer.

A pointer to your array has the type Organism* (*)[20][20].

A pointer to the first element of the array is probably what your friend had in mind, but that has the type Organism* (*)[20], not Organism** or Organism***, and can't be converted to either.

(And, as a bonus, worldTab[20] is out of bounds because it would be the twenty-first array of the twenty that exist. And you never initialised temp before assigning to *temp, which is the source of the access violation.)

While you could write

Organism* (*getWorldTab())[20] {
    return &worldTab[0];
}

Organism* (*temp)[20] = getWorldTab();

or simply

Organism* (*temp)[20] = worldTab;

I think you should learn to use std::vector and std::array – they relieve a lot of pain.
(Plus, it's 2017. While it can be interesting, there's no need to program like it's 1969.)

Sign up to request clarification or add additional context in comments.

Comments

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.