0

IDE gives me this error when I try to compile:

random.h|11|error: expected ',' or '...' before 'arr'|
amongst others but this is the one that is my biggest problem.

I can do this in my main function but I want to do it by calling a function that will initialize any 2D array I give it. Then I have another function for printing the array, but they more or less are the same thing except for the statements. I'm a complete beginner so please feel free to have a few laughs!

    void InitializeArray2D(int& arr[int x][int y])
{
    for (int i=0; i<x; i++)
    {
        for(int j=0; j<y; j++)
        {
            cout<<"arr["<<i<<"]["<<j<<"]=";
            cin>>arr[i][j];
        }
    }
}
The_0bserver
  • 11
  • 1
  • 2

2 Answers2

1

In fact

int& arr[x][y]

(I removed syntaxical incorrect type specifiers of x and y) is a declaration of a pointer to an array of references. C++ does not allow to declare arrays of references.

The correct declaration will be

void InitializeArray2D(int ( & arr )[x][y]);

provided that x and y are defined as constant.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Laughs aside, your function prototype is very mangled.

you'll want something more like:

void InitializeArray2D(int &arr[][], int x, int y) {
}

or

void InitializeArray2D(int **arr, int x, int y) {
}

Note: this assumes your array is allocated already

also, do yourself a favor and make your outer loop y and inner loop x, not that it matters all that much, but it makes visualizing it easier.

Edit: As Ed S. kindly and accurately pointed out, using x as your inner loop does matter in terms of data locality. Get used to doing it that way sooner rather than later.

cioffstix
  • 81
  • 2
  • 2
    *"also, do yourself a favor and make your outer loop y and inner loop x, not that it matters all that much"* - sure it does; locality of data – Ed S. Jan 30 '14 at 21:17
  • 1
    or do yourself a favor and use `std::vector` or `std::array`. P.S: Nice avatar ;) – Borgleader Jan 30 '14 at 21:19
  • Now it gives me: /Users/ravynb/Desktop/work/random.h|23|error: declaration of 'arr' as array of references| – The_0bserver Jan 30 '14 at 21:23
  • Remove the &, or pass the array as a double pointer, c++ doesn't allow arrays of references. That was my mistake. – cioffstix Jan 30 '14 at 21:25
  • And now it is saying that x and y were not declared in this scope. I'm guessing my idea is a bit impractical – The_0bserver Jan 30 '14 at 21:35