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.

  • The expression `*mtr[l][m]` does not do what you think it does because of [*operator precedence*](http://en.cppreference.com/w/c/language/operator_precedence). – Some programmer dude May 19 '16 at 07: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). – Some programmer dude May 19 '16 at 07:02
  • Thank you very much guys , i've been stuck with this for hours. – Nico Baldelli May 19 '16 at 07:30

1 Answers1

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;

}
J. Chomel
  • 8,193
  • 15
  • 41
  • 69
Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31