I'm currently having problem with my homework which ask us to create a program that solve matrix problems using pass by reference, and I just cant understand how is it done. can someone show me a simple code that solve matrix addition using pass by reference. thanks..
-
1[What have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – Some programmer dude Nov 21 '12 at 13:35
-
Use google. You will find the solution quickly. – qwertz Nov 21 '12 at 13:39
-
That's basicly the whole homework task. Break it down, google pass by reference in c (or search on here), then google matrix addition (or search on here). – weston Nov 21 '12 at 13:42
1 Answers
Let's say we have mat4_t type and mat4_add function defined.
typedef ... mat4_t;
With "by copy" approach will look like this:
mat4_t mat4_add(mat4_t m1, mat4_t m2);
mat4_t m1, m2, m3;
m3 = mat4_add(m1, m2);
Function mat4_add takes 2 arguments and returns new matrix (by copy).
With "by reference" it would be:
void mat4_add(mat4_t *sum, const mat4_t *m1, const mat4_t *m2);
mat4_t m1, m2, m3;
mat4_add(&m3, &m1, &m2);
Function receives pointers to both source matrices (m1, m2) and pointer to memory where it should store matrices sum.
With first approach: Both m1 and m2 are copied to the function stack, thus stack grows by 2*sizeof(mat4_t) and matrices data is copied. Later, function stack grows by another sizeof(mat4_t) to store calculation result. That result is copied once again with return statement when value is assigned from function return value.
On the other hand with pointers "by reference", coping is not necessary. That approach is faster (don't need copies) and more memory efficient.
Also, there is no such thing like copy by reference in C. Everything is passed by value. what happens during pass by reference in C?

- 1
- 1

- 789
- 12
- 22