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.

1

2 Answers 2

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 }}
};
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I'll look more into vectors and arrays from the std thing, I never really knew anything about them.
@lemondrop I've updated my answer with links to reference pages for the standard containers.
@lemondrop: There is std::complex as well.
@JoachimPileborg How would you pass a vector thing like that to a class? Do they work the same way as normal arrays? Edit: Apparently you can just do foo(vector<array<int,2>> ptr) : stored(ptr) {}, so nevermind
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.

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.