Struct declaration and initialization outside the main function in C

Asked

Viewed 591 times

1

I’m playing a little game in C that has the card structure:

typedef struct {
    int numero;
    int cor;
} TipoCarta;

A method to put the values in the chart:

void inicializaCarta(TipoCarta *carta, int num, int cor){
    carta->numero = num;
    carta->cor = cor;   
}

And in the main I will have to declare and initialize each card by passing the values, for example:

TipoCarta amarelo1, amarelo2;
inicializaCarta(&amarelo1, 1, amarelo); 
inicializaCarta(&amarelo2, 2, amarelo);

(in the header has a constant setting an integer to yellow)

It is possible to do this initialization in another file . c, or at least outside of main? Pro code does not get so "polluted" as it will have many cards.

  • 1

    It seems possible, but I’m not sure I understand the exact doubt.

1 answer

2


If the problem is pollution, you could rewrite your main() another way, look at this:

typedef enum { corVermelho, corAzul, corVerde, corAmarelo } TipoCor;

typedef struct {
    int numero;
    TipoCor cor;
} TipoCarta;

void inicializaCarta( TipoCarta * carta, int num, TipoCor cor ){
    carta->numero = num;
    carta->cor = cor;
}

int main( void ) {
    int i = 0;

    TipoCarta amarelo[10];
    TipoCarta azul[10];
    TipoCarta verde[10];
    TipoCarta vermelho[10];

    for( i = 0; i < 10; i++ ) {
        inicializaCarta( &vermelho[i], i + 1, corVermelho );
        inicializaCarta( &azul[i], i + 1, corAzul );
        inicializaCarta( &verde[i], i + 1, corVerde );
        inicializaCarta( &amarelo[i], i + 1, corAmarelo );
    }

    return 0;
}

In the above example, 10 letters of 4 different colors were initialized, totaling 40 cards.

Alternatively, you can put your Cartas within a Deck, look at you:

typedef enum { corVermelho, corAzul, corVerde, corAmarelo } TipoCor;

typedef struct {
    int numero;
    TipoCor cor;
} TipoCarta;

typedef struct {
    TipoCarta amarelo[10];
    TipoCarta azul[10];
    TipoCarta verde[10];
    TipoCarta vermelho[10];
} TipoDeck;

void inicializaCarta( TipoCarta * carta, int num, TipoCor cor ){
    carta->numero = num;
    carta->cor = cor;
}

void inicializaDeck( TipoDeck * deck )
{
    int i = 0;

    for( i = 0; i < 10; i++ ) {
        inicializaCarta( &deck->vermelho[i], i + 1, corVermelho );
        inicializaCarta( &deck->azul[i], i + 1, corAzul );
        inicializaCarta( &deck->verde[i], i + 1, corVerde );
        inicializaCarta( &deck->amarelo[i], i + 1, corAmarelo );
    }
}

int main( void )
{
    TipoDeck deck;
    inicializaDeck( &deck );
    return 0;
} 
  • very interesting, I’ll test, thank you :)

Browser other questions tagged

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