2

Sorry i am new to c, i am trying to pass this matrix to a procedure by reference so i don't have to copy it in memory. I couldn't find any explanation. This is the closest i could get but it doesn't work. The point of the program is only for that, i made it to test it.

#include <stdio.h> typedef int tmatrix[5][5]; void print (tmatrix*mtr) { int l , m; l=0; while (l<=4) { m=0; while (m<=4) { printf("%d", *mtr[l][m]); m = m+1; } printf("\n"); l=l+1; } } //----------------------------------- int main() { int i , j; tmatrix matrix; i=0; while (i <= 4) { j=0; while (j<=4) { matrix[i][j] = 3; j = j+1; } i = i+1; } print(&matrix); return 0; } 

It should print:

33333 33333 33333 33333 33333 

But it prints:

33333 54198992041990930 1977890592-1961670060002752492 03232520 664-21479789407743168 

I know it may be something to do with the pointers because i think those are addresses, but i got no clues.

3
  • The expression *mtr[l][m] does not do what you think it does because of operator precedence. Commented May 19, 2016 at 7:00
  • You also have to remember that arrays naturally decays to pointers to their first element, so there's no need to pass arrays by reference (or rather emulate passing by reference, since C doesn't have it). Commented May 19, 2016 at 7:02
  • Thank you very much guys , i've been stuck with this for hours. Commented May 19, 2016 at 7:30

1 Answer 1

3
  1. matrix is a 2D array of integers. You can directly pass it to the function. Passing an array will be the same as passing it by reference.
  2. The printf inside the function will also be changed to directly access it. *mtr[l][m] --> mtr[l][m]
  3. While calling it, you can call it directly as shown. print(&matrix) --> print(matrix)

The modified code is below.

#include <stdio.h> typedef int tmatrix[5][5]; void print (tmatrix mtr) { int l , m; l=0; while (l<=4) { m=0; while (m<=4) { printf("%d", mtr[l][m]); m = m+1; } printf("\n"); l=l+1; } } //----------------------------------- int main() { int i , j; tmatrix matrix; i=0; while (i <= 4) { j=0; while (j<=4) { matrix[i][j] = 3; j = j+1; } i = i+1; } print(matrix); return 0; } 
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much Rishikesh Raje. But can i ask you, what if i want to pass it by value?
@NicoBaldelli in C, arrays are always passed by reference. You cannot pass it by value.
@RishikeshRaje, wrong, all is passed by value in C, but an array decays into a pointer
So, effectively, you cannot pass an array by value, right?
Not directly, the only way is embedding the array into a struct and passing a pointer to this struct

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.