0

I am trying to pass two multidimensional arrays as reference arguments to a function in C++.

The prototype is written like this:

void func(char (&foo)[4][4], char (&bar)[4][4]); 

My problem is that the second argument does not get passed as a reference argument, but the first one does. If I change their placement – so (&foo)[4][4] is second and vice versa – foo does not get passed as a reference but bar does.

However if I add a third argument, the second argument gets passed as reference.

How can I fix this without having to add another useless argument?

6
  • What do you mean by "it does not get passed as a reference"? Commented Dec 11, 2011 at 16:42
  • 2
    Show your calling code. I'm pretty sure the error's there. Commented Dec 11, 2011 at 16:43
  • 1
    What else does it get passed as ? Copy ? No way in c++. C++ passes arrays as reference even if you think you're passing a copy. Commented Dec 11, 2011 at 16:44
  • 1
    Please post some actual code that demonstrates the problem (see sscce.org). Commented Dec 11, 2011 at 16:48
  • 1
    Post the whole related thing and show what you can't change. I am pretty sure that function is able to change it's callers memory. Commented Dec 11, 2011 at 16:51

3 Answers 3

3

Try to minimize the size of the proverbial foot to shot yourself into by using typedefs:

typedef char charray44[4][4]; void foo(charray44 & one, charray44 & two); 

This should work as expected; and if not, you should be able to set up a simple test harness to figure out where (else) in the code you are making a mistake.

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

Comments

1
void foo(char (&one)[4][4], char (&two)[4][4]){ } int main(){ char one[4][4]; char two[4][4]; foo(one, two); } 

Compiles fine on MSVC, GCC and Clang. Your problem lies elsewhere.

Comments

1

As an addition to Xeos solution, a perhaps better way to solve this problem would be to encapsulate the array and pass the new object by reference.

class matrix{ std::vector<char> values; size_t x_sz, y_sz; public: matrix(size_t x, size_t y) : values(x*y), x_sx(x), y_sz(y) {} char& get_at(size_t x, size_t y) { return values[y*x_sz+x]; } const char& get_at(size_t x, size_t y) const { return values[y*x_sz+x]; } }; 

then you can just pass to funcs like.

 void f(const matrix& a); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.