Help needed to understand how reference of a vector works as function parameter

Hi, I'm a newbie in C++. I'm facing weird behavior when pass a vector as reference to my function. Here's the code snippet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
void TransposeMatrix (vector<int> &matrix, int N, int M)
{
	assert ( N != M );
	for(int i = 0; i < N*M - 1; i++) 
	{
		int oldPos = i ;
		int newPos = (N*oldPos) % (N*M - 1);
		while ( newPos != i ) {
			matrix [newPos] = matrix [oldPos];
			oldPos = newPos;
			newPos = (N*oldPos) % (N*M - 1);
		}
		matrix [i] = matrix [oldPos];
	}
}
 
int main()
{
	int row, col ;
	cin >> row >> col ;
	vector <int> A (row * col);	

	for(int i = 0; i < row; i++)
		for(int j = 0; j < col; j++)
			cin >> A [i*col + j] ;

	TransposeMatrix (A, row, col);
	
	for(int i = 0; i < col; i++) {
		for(int j = 0; j < row; j++)
			cout << setw(3) << A [i*row + j] << " ";
		cout << endl;
	}

	return 0;
}

In this program, the function is modifying the content of vector<int> matrix. Hence, I need to pass a reference. However, the program gives bizarre output. You can see the program output here : http://ideone.com/ct28w

The surprising fact is that when I pass the matrix as value, it shows correct output. You can see the program output here : http://ideone.com/a3UkO

Btw, this is not any homework problem. So, please help me with your suggestions. Thanks in advance.
Note that your for loops are different. This is why passing by value gives correct answer. Delete line 27 and see for yourself that it does nothing (when you pass by value).

I'm not sure what your transpose function is doing (it looks complicated)..
Topic archived. No new replies allowed.