0

My question is kinda simple and probably silly, but if I have a dynamic matrix like int ** max and I pass it to a function calculateCost(int ** max, int n)).

My question is: how can I pass it as const reference?

Carlos Cavero
  • 3,011
  • 5
  • 21
  • 41
Laura Galera
  • 89
  • 1
  • 10

1 Answers1

0

It is not possible to have a pass a pointer reference (see this answer).

Because references are not objects, there are no arrays of references, no pointers to references, and no references to references:

int& a[3]; // error
int&* p;   // error
int& &r;   // error

You may wanna use the STL's vector to replace every pointer you have. int calculateCost(const std::vector> &max, int n);

This will allow you to do all the basic operators a pointer can do, but with extra stuffs like easier init, resize, and ranged_for_loops.

template<typename T>
using matrix_t = std::vector<std::vector<T>>;

size_t width = 5, height = 3;
// std::vector<std::vector<int>> is the same as matrix_t<int>
matrix_t<int> my_matrix(height, std::vector<width, 0>);

Here are some useful links to replace malloc, new, delete...
- 2d vector from 2d const array
- unique_ptr
- shared_ptr
- make_unique
- make_shared

Have a happy new year !

EDIT: As said in the above comments, there is no use to use refs in your case, you can just use const double pointers

TCLNA
  • 1
  • 1
  • 4
    A reference to a pointer is fine. You're saying a pointer to a reference isn't possible, but that's not the same thing at all. – Mat Jan 02 '20 at 17:17
  • Thanks, should i edit it to "You cannot pass a pointer reference" ? Also i don't understand "A reference to a pointer is fine." – TCLNA Jan 02 '20 at 17:25
  • What I wished was something like const int ** &m because, correct me if I am wrong, the m of the method is a copy (I have copy constructor) – Laura Galera Jan 02 '20 at 21:17
  • Pointers avoid copy construction, you can just do `const int **m` – TCLNA Jan 03 '20 at 00:24