0

can someone help? i'm trying to create a function for reading a 2D array and then display it in int main(). i get the following error when running the code: "error: invalid types ‘int[int]’ for array subscript" on the line with cin >> v[i][j].

i'm confused because this seems to work with 1D arrays ( f(&v[0]) and void f(int* v, int* n)) so why wouldnt it work in this case as well?

#include <iostream>

using namespace std;

void f(int* v, int* n, int* m)
{
    cin >> *m >> *n;
    int i, j;
    
    for(i=0; i<*m; i++)
        for(j=0; j<*n; j++)
           {
            cin >> v[i][j];
           }

}

int main()
{
    int i, j, m, n, v[10][10];
    
    f(&v[0][0], &n, &m);
    
    for(i=0; i<m; i++)
        { for(j=0; j<n; j++)
            cout << v[i][j] << " ";
            cout << endl;
        }
            return 0;
}

1 Answer 1

1

In your code the type of v in function f is a pointer to int, while it should be a pointer to a fixed-length array of int. Should be:

void f(int* v[10], int* n, int* m)

or equivalently

void f(int v[][10], int* n, int* m)

Also, by passing &v[0][0], you are passing v[0] to the function. You need to pass v (which is the same as &v[0], but you can write just v).

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

5 Comments

But a pointer to an array is not a pointer to a pointer. The type of &v[0] is int(*)[10], not int**, and there is no conversion between those two.
@molbdnilo Arrays decay to pointers though when passed to a function. 2-dimensional arrays decay to pointers of pointers and so on.
Oh, I see now that &v[0][0] is passed. Really, v by itself should be passed (while having the function accept a pointer to a pointer as in my answer) or else you now have a type of 1D array and you can't index v in this fashion - v[i][j] anymore. Edited the answer.
No, a 2-D array does not decay into a pointer to a pointer; an array decays into a pointer to its first element. If you have int v[10]10], v decays into a int(*)[10] – that is, &v[0] – a pointer to an array of ten ints. There is no conversion from int(*)[10] into int**. (Which you will notice if you attempt your suggestion.)
@molbdnilo Oops, you are right. The function has to know how long are the previous dimensions of the array, so that the compiler knows to how many bytes is equivalent each index of the array.

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.