How to create a function with matrix and then use it in the main int by substituting values from another matrix?

Asked

Viewed 56 times

1

I’m wondering how to create a function where you will use the values of an int main matrix, and then how to replace the values obtained in the function matrix for the int main matrix?

I was creating the function so:

int JogadaComp2 (int tabuleiro[3][3])

 {

 if ( tabuleiro [2][2] = 0) { tabuleiro[2][2] = 1;return 0;} 

 if ( tabuleiro [1][1] == 2 && tabuleiro [1][2] == 2 && tabuleiro [1][3] == 
0) { tabuleiro[1][3] = 1;return 0;}

if ( tabuleiro [1][1] == 2 && tabuleiro [2][1] == 2 && tabuleiro [3][1] == 
0) { tabuleiro[3][1] = 1;return 0;}

return tabuleiro[3][3];

}

and to replace the values in the int main matrix:

int main (){

int tabuleiro[3][3];

tabuleiro[3][3] = JogadaComp2(tabuleiro[3][3]);

for(l=0;l<3;l++)
{
    for(c=0;c<3;c++)
    {   
    printf("%d", tabuleiro[l][c];
 }
 printf("\n";
}

return 0;

}

1 answer

1


If you just want the function to change values in the matrix tabuleiro does not need to have a kind of feedback and can simply leave as void. It also simplifies itself once you no longer need the returns:

void JogadaComp2 (int tabuleiro[3][3]) {

    if (tabuleiro[2][2] = 0) {
        tabuleiro[2][2] = 1;
    }

    if (tabuleiro [1][1] == 2 && tabuleiro [1][2] == 2 && tabuleiro [1][3] == 0) {
        tabuleiro[1][3] = 1;
    }

    if (tabuleiro [1][1] == 2 && tabuleiro [2][1] == 2 && tabuleiro [3][1] == 0) {
        tabuleiro[3][1] = 1;
    }
}

In main you have to call this function without capturing its return:

JogadaComp2(tabuleiro);

Note that when you pass a matrix as a parameter to a function, the indices are not specified, otherwise you would be passing a specific value instead of the whole matrix.

I take this opportunity to say that there were also some misspellings in your main code:

for(l=0;l<3;l++)
{// ^---- l não foi declarado
    for(c=0;c<3;c++)
    {// ^---- c também não foi declarado
    printf("%d", tabuleiro[l][c];
    //  ------------------------^ falta o ) de fecho
 }
 printf("\n";
 -----------^ falta aqui também o ) de fecho
}
  • The spelling mistakes are due to me summarizing the code to clear my doubts, I just summed up the part I wasn’t able to do. But anyway thanks for the reply.

  • @Renanmela Of nothing. Did well to summarize, the goal is always to have the minimum necessary only for the problem in question. I chose to point out anyway because I was in doubt whether I really had the mistakes or not, and if I did, I also knew what to fix.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.