adriano
adriano

Reputation: 11

Problem when I try pass a struct pointer to a function

Whats's wrong with this code?

typedef struct jogador{
    char nome[7];
    int pecas[6][2];
}Jogador;

void distribuir_pecas( Jogador* jogadores );

int main()
{
    Jogador* jogadores;
    jogadores = (Jogador*) malloc( 4 * sizeof(Jogador));
    distribuir_pecas( jogadores );
    return 0;
}
void distribuir_pecas( Jogador* jogadores ){
    int domino[28][2];
    int vetor_aux[28];

    int i, j;
    int peca_sorteada;
    int num_jogador = 0;
    int num_domino = 0;
    srand(time(NULL));

    for( i = 0; i < 28; i++){
        vetor_aux[i] = 1;
    }
    for( i = 0 ; i < 7; i++){
        for( j = 0; j < 7; j++){
            if( j == 0 ){
                j = i;
            }
            domino[num_domino][0] = i;
            domino[num_domino][1] = j;
            //printf("%d*%d\n", domino[num_domino][0], domino[num_domino][1]);
            num_domino++;
        }
    }

    while( num_jogador < 4 ){
        for( i = 0; i < 6; ){
            peca_sorteada = rand()%28;
            if( vetor_aux[peca_sorteada] ){

                vetor_aux[peca_sorteada] = 0;
                jogadores[num_jogador].pecas[i][0] = domino[peca_sorteada][0];
                jogadores[num_jogador].pecas[i][1] = domino[peca_sorteada][1];
                i++;
                printf("[%d|%d]\n",jogadores[num_jogador].pecas[i]                        [0],jogadores[num_jogador].pecas[i][1]);
            }
        }
        printf("\n\n");
        num_jogador++;
    }
}

When I try equate domino[peca_sorteada][0] to jogadores[num_jogador].pecas[i][0], for exemple, using a -> operand a compilation error ocurrs, but with . operand the printf don't print the correct value. Why????

Upvotes: 1

Views: 279

Answers (1)

Cameron Skinner
Cameron Skinner

Reputation: 54276

Not sure if this is the underlying problem, but this:

int domino[28][2];
....
for( i = 0 ; i < 7; i++){
    for( j = 0; j < 7; j++){
        if( j == 0 ){
            j = i;
        }
        domino[num_domino][0] = i;
        domino[num_domino][1] = j;
        //printf("%d*%d\n", domino[num_domino][0], domino[num_domino][1]);
        num_domino++;
    }
}

is going to cause you problems. num_domino will be 49 by the end of this double loop, but the domino array is only 28 elements long.

Upvotes: 3

Related Questions