-1

I'm new to C++ and still really confused about how 2d arrays work with pointers. If I have this (in example format):

int* anarray = anarrayfiller();
for (int a=0;a<10;a++) {
    for (int b=0;b<10;b++) {
         cout<<(char)anarray[a][b]; //Here's the error mentioned below
    }
    cout<<"\n";
}
//Later, outside main
int* anarrayfiller() {
    int anarray[10][10];
    //Populated here
    return &anarray;
}

This produces an error under b in the cout<< line: "Expression must have pointer-to-object type" I would just check how to search through 2d arrays, and I found this: A pointer to 2d array Which suggests that actually this pointer points to the array of ints inside anarray[0], and if that's the case, I must be missing something in terms of returning pointers - wouldn't I then have to return a pointer to a 2d array of pointers that each points to a specific int from anarray? I'm pretty confused here. How do pointers work with 2d arrays?

1 Answer 1

3

You have a few errors here:

  1. You return a pointer to a local variable. After the function returns the stack area previously occupied by that variable no longer exist, or is used by the next function.

  2. You return a pointer to an integer, while you have a two-dimensional array. The closest would be a pointer-to-pointer.

  3. You access thing single-pointer as though it was a double-pointer (pointer-to-pointer or pointer-to-array or array-or-arrays), but it's not. That's the reason you get errors at the pointed to line.

  4. But you can't use pointer to pointer, as the memory layout of an array-of-arrays (a two-dimensional array) is different from a pointer-to-pointer. See e.g. this old answer of mine for an explanation of why.

This can be solved most easily by creating the array dynamically on the heap, as a pointer-to-pointer:

int **anarrayfiller()
{
    int **anarray = malloc(sizeof(int *) * 10);

    for (int i = 0; i < 10; ++i)
    {
        anarray[i] = malloc(sizeof(int) * 10);

        /* Populate here */
    }

    return anarray;
}

As you tagged your question as C++, you should actually avoid plain arrays or pointers in favor of either std::vector (if you need to add dynamically) or std::array (if you have a fixed compile-time size):

std::array<std::array<int, 10>, 10> anarrayfiller()
{
    std::array<std::array<int, 10>, 10> anarray;

    // Populate arrays

    return anarray;
}
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.