How to create an array function and then use it in int main by replacing values in another array?

1

I am having a question about how to create a function where I will use the values of an array of int main, and then how to override the values obtained in the array of the function for the array of int main?

I was creating the function like this:

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 array of int main:

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;

}
    
asked by anonymous 15.10.2017 / 23:35

1 answer

1

If you only want the function to change values in the array tabuleiro , you do not need to have a return type and you can simply leave it as void . By itself also simplifies since it no longer needs 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;
    }
}

No main has to call this function without capturing its return:

JogadaComp2(tabuleiro);

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

I'd like to say that I also had some typos 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
}
    
16.10.2017 / 01:48