Hi guys!
I'm pretty new to C++. I am currently on freshman year at college, and have a programming problem (not homework, it's actually a side project of mine) that consists on implementing some algebra-related functions on C++.


I'll go straight to the point:

int switchlines(int i, int j, int dim, int matrix[2][2]){ 
	int aux;
	for(int index = 0; index < dim; index++){
		aux = matrix[i][index];
		matrix[i][index] = matrix[j][index];
		matrix[j][index] = aux;
		}
	return 1;

Now, as far as I know, when I pass an array to a function, I don't need to pass as reference, since it already does. Now, why the heck doesn't the matrix have its lines switched when I cout it later on the main?


Thanks a lot in advance =D
[PS: I've made the funcion an int so I can have return values, in case I need to debug something later on or so. If I finish the program and don't actually have a use for it, I'll just turn it into void...)

Recommended Answers

All 6 Replies

This part :

for(int index = 0; index < dim; index++){
		aux = matrix[i][index];
		matrix[i][index] = matrix[j][index];
		matrix[j][index] = aux;
		}

What do you think its doing? Were you trying to swap ?

That part is supposedly switching lines i and j of the matrix, given the matrix's dimension.
Is there something wrong with it? =/

I was able to get it work as you have it with this output:

Before
1 2
3 4

After
3 4
1 2

I hate to ask, but we all get these moments, were you trying to swap rows 1 and 2?

I was able to get it work as you have it with this output:

Before
1 2
3 4

After
3 4
1 2

I hate to ask, but we all get these moments, were you trying to swap rows 1 and 2?

Yes, I was. Why the heck doesn't it swap the rows here, then? O.o

PS: don't tell me there's a pre-made function to swap 2 lines in a matrix xD

I'm gonna look a little deeper into it...

You want to swap row 0 and row 1 instead. The way you have your function laid out it'd be accessing garbage adjacent to your 2D array when you access the non-existent row 2.

You want to swap row 0 and row 1 instead. The way you have your function laid out it'd be accessing garbage adjacent to your 2D array when you access the non-existent row 2.

DAMMIT! (sorry...)

When I first wrote the program, on int main, to test it out, I made a newb's mistake, doing something like

int matrix[2][2];
matrix[1][1] = 1;
matrix[1][2] = 2;
matrix[2][1] = 3;
matrix[2][2] = 4;

before noticing I was trying to write on the wrong place in memory. Oh well...

Thanks a lot for your help =D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.