0

I am not very good with c++ and was wondering why an error happens with arrays inside of arrays, but works fine with a normal array (and how to fix it possibly).

Heres the code (just trying to store an array inside a class upon constructing it):

class foo {
    int* stored;
public:
    foo(int* ptr) {
        stored = ptr;
    }
};

int main() {
    int arr[][2] = {{1,4},{5,7},{2,5}};
    foo obj(arr);
}

When the array is something like int arr[] = {1,2,3} it works without errors, but the normal code gives me this error:

error: no matching function for call to 'foo::foo(int [3][2])'

I searched around for a while, but I don't really know what to search for in the first place, which is why I am asking here (but I feel it has something to do with pointers). Thanks for any help.

Lemon Drop
  • 2,113
  • 2
  • 19
  • 34
  • @texasbruce An array of arrays is **not** the same as a pointer to a pointer. See e.g. [this answer of mine to see why](http://stackoverflow.com/a/18440456/440558). – Some programmer dude Sep 22 '13 at 00:13

2 Answers2

1

You try to pass an array of arrays of integers as a single integer pointer, which will not work. While it's true that an array decay to pointer when passed, an array of arrays can not be a single pointer, and not a pointer to pointer either.

It can however be used as an pointer to array:

class foo
{
    int (*stored)[2];

public:
    foo(int (*ptr)[2]) : stored(ptr) {}
};

The parentheses in the declaration is needed because otherwise it would be an array of pointers.

However, I would recommend against using raw arrays, and move to std::vector or std::array, which of course can be nested:

std::vector<std::array<int, 2>> arr = {
    {{ 1, 2 }},
    {{ 3, 4 }}
};
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Firstly your code (even if it worked) would not store an array. In your class you have a pointer so all you are storing is a pointer to an array. It is important to get these distinctions clear in your head.

You have to declare a pointer that is compatible with the array you are trying to 'store'. That pointer is int (*stored)[2], that is a pointer to an array of two ints.

Its actually pretty simple

int* is compatible with int[]
int (*)[N] is compatible with int[][N]
int (*)[N][M] is compatible with int[][N][M]

etc. etc. But the parentheses do confuse people. They are necessary because the * operator has a lower priority than the [] operator.

john
  • 85,011
  • 4
  • 57
  • 81