-1

Reading some others questions about passing 2d arrays I realized that no one answered this:

void func(int **&matrix) {
    matrix[2][1]=5;
    ...
}

int main() {
    int **matrix;
    matrix=new int*[10];
    for(int q=0;q<10;q++)
        matrix[q] = new int[5];
    func(matrix);
    ...
}

I tested it and it works. Any problem with this code?

Bill Lynch
  • 72,481
  • 14
  • 116
  • 162
Lopo Kima
  • 1
  • 1

1 Answers1

0

The answer is the same as why shouldn't you use int*& when passing 1D arrays represented via a pointer. You want to use the reference whenever you want to modify the pointer passed to your function. In your case, you are just accessing the elements that are pointed by, no need to modify the pointer itself. So, there is no real need for a reference, although it is not technically incorrect to use a reference.

Example of when it may make sense to use a reference:

f(int*& p)
{
    // do something with the memory pointed by p
    for(int i = 0; i < 10; ++i)
        std::cout << ++p[i]; // ok, modify the memory location p+i points to
    delete[] p; // deallocation
    p = nullptr; // nullify p, if you want to modify what you passed, you need the reference
}
vsoftco
  • 52,188
  • 7
  • 109
  • 221
  • @user3528438 why would it matter if its a POD or not – sp2danny May 02 '15 at 02:22
  • @user3528438 that's no different from "who changed my string" – sp2danny May 02 '15 at 02:27
  • 2
    @user3528438 modifying PODs or non-PODs is perfectly fine, provided that's the intention. Aside from passing by `const` reference, this is probably the other important use of references in C++. – vsoftco May 02 '15 at 02:28