"Return temp;" issues

I've been working on a part of my program designed to multiply two matrices:
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
37
38
39
40
matrix & matrix::operator*(const matrix &mat){
	matrix temp = mat;
	matrix Transpose_mat = temp.transpose();
/**/matrix result (rows, Transpose_mat.rows);
	
int R,C;
	R = rows;
	C = mat.columns;
	int size = R*C;
	

	delete[] temp.data;		// Clear the data for the temporary matrix
    temp.data = new double[size];	// Recreate the array with null values
    for(int k(0); k<size; k++){		// Reload temp with data (first item)
        temp.data[k]=data[k];	// reassign each
    }
	delete[] result.data;
	result.data = new double [size];

	int addr(0);
	double hold(0);

	if (columns==Transpose_mat.columns){
		for (int a(0); a < R; a++){
			for (int b(0); b < C; b++){
				for (int c(0); c < C; c++){
					int l = b*C+c;
					int m = a*C+c;
					hold+=temp.data[m]*Transpose_mat.data[l];
				}
				result.data[addr]=hold;
				hold=0;
				addr+=1;
			}
		}
	}

		cout << "End of multiplication process reached:" << endl;
		return result;		//	Does not like this in this context...
}


The code I'm testing it with is:
1
2
3
4
5
6
7
8
9
10
11
12
int main(){
	matrix A(2, 2);
	matrix B(2, 1);
	A.AssignOp(1,2,3,4);
	B.AssignOp(10,20);
	cout << "A = \n" << A << endl;
	cout << "B = \n" << B << endl;
	matrix C = A*B;
	cout << C;
        return 0;
}
	


When the program is run however, there is no output printed beyond "End of multiplication process reached".

The actual processing seems to work - if I add cout << result at the end, the function will print the correct matrix result, but by having return result, the compiler warns that the function is "returning address of local variable or temporary". Which is true, the result matrix is created for the operation - which would lead me to think the issue is with the "return result;" line.

However, on my addition and subtraction overloads, both return an object created within the scope of their respective overload functions and no qualms are made of it.

What is it I'm missing here?
The return type of your function is matrix& - a reference. References work like pointers. After a function is executed the memory it used will be reused by other functions, to pointing to is not going to work. Remove the & to return by value.
Now I feel like an idiot - turns out I'd done that with the other overloaded functions I talked about...I just missed it in this case when I had copied it across from a previous program.

Thanks a lot!
Topic archived. No new replies allowed.