View Full Version : Question About Arrays inside functions

14th June 2011, 23:09

I am working in a simple QConsole application, and what I want to do now is some matrix operations.

Let me explain on the go:

Outside my main as global variables I have defined two matrices:

QVector<QVector<int> > A, B;

Inside the main, I set the sizes to them using:

for(int i=0; i<10; i++)

And then I fill the A matrix with random values from 1 to 10.

What I want to do in some point, is to multiply matrix A by some scalar, but I want the result to be stored in matrix B.

So, I wrote the following void function:

void Multiply(int scalar, int rows, int cols, QVector<QVector<int> > matrix, QVector<QVector<int> > result)

for(int i=0; i<rows; i++)
for(int j=0; j<cols; j++)


And then, inside main, I call, for example:

Multiply(5, 10, 10, A, B);

But the function is not working because matrix B ends up with all values to 0.
However, if I debug and print the values of result[i][j] inside my function, it shows the correct values for the operation.

Do you know why is that happening?

I tried the same multiply function using regular C arrays:

void Multiply(int scalar, int Matrix[10][10], int Result[10][10])

And it works well that way...

Can you tell me why my void function is not working properly? Should I try some other way to do the same, since I wanted to do some matrix operations the same way, for example, multiply matrix A with B, and store the result in other matrix C, using some similar void function.


14th June 2011, 23:17
You're passing your matrices by value. This results in a copy being made when the function is entered; all operations take place on those copies, not on the original matrices.

You need to pass them by reference

QVector<QVector<int> >& matrix, QVector<QVector<int> >& result

(Note the ampersands.)

The C-style version works because you are effectively doing the same thing. You're passing in a pointer to the external arrays, not a copy. Pass-by-reference works exactly the same way, while providing some syntactic sugar by eliminating the need to dereference the arguments.

15th June 2011, 02:52
QVector<QVector<int> >& result

15th June 2011, 15:27
It Worked! Thanks!!!