Passing by reference of a structure with vector in C!

0

I have the following code:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    #define TAM 3

    typedef struct{
       char nome[50];
       char musica[50];
       int integrantes;
       int ranking;
    }Banda[TAM];

    void ler(Banda *banda){
       int i=0;
       for(i=0;i<TAM;i++){
           printf("Nome da banda: ");
           fgets(banda[i]->nome,50,stdin);
           fflush(stdin);
           printf("Tipo de musica: ");
           fgets(banda[i]->musica,50,stdin);
           fflush(stdin);
           printf("Numero de integrantes: ");
           scanf("%i",&banda[i]->integrantes);
           fflush(stdin);
           printf("Posicao: ");
           scanf("%i",&banda[i]->ranking);
           fflush(stdin);
           printf("\n\n");
       }
    }

void mostrar(Banda banda){
    int i=0;
    for(i=0;i<TAM;i++){
        printf("Banda %i\n\n",i+1);
        printf("Nome da banda: %s\n",banda[i].nome);
        printf("Tipo de musica: %s\n",banda[i].musica);
        printf("Integrantes: %i\n",banda[i].integrantes);
        printf("Posicao: %i\n",banda[i].ranking);
    }
}

int main(){
   Banda banda[TAM];
   ler(&banda);
   mostrar(banda);
   return 0;
}

I can read the 3 positions with the ler() function, but at the time of writing with the mostrar() function, only the first position is written correctly, the other two do not, (random letters and numbers appear). Thanks for the help.

    
asked by anonymous 15.03.2016 / 20:19

1 answer

0

The declaration of the struct does not need a size, as it is instantiating a vector of struct in main, or methods to read and write must receive vectors (pointers), when picking the position of a vector / pointer, -> and yes . .

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TAM 3

typedef struct{
    char nome[50];
    char musica[50];
    int integrantes;
    int ranking;
}Banda;//////////////////////////

/////////////////
void ler(Banda banda[]){
    int i=0;
    for(i=0;i<TAM;i++){
        printf("Nome da banda: ");
        scanf("\n%50[^\n]",banda[i].nome);
        printf("Tipo de musica: ");
        scanf("\n%50[^\n]",banda[i].musica);
        printf("Numero de integrantes: ");
        scanf("%i",&banda[i].integrantes);////////
        printf("Posicao: ");
        scanf("%i",&banda[i].ranking);///////
        printf("\n\n");
    }
}

////////////////////////
void mostrar(Banda banda[]){
    int i=0;
    for(i=0;i<TAM;i++){
        printf("Banda %i\n\n",i+1);
        printf("Nome da banda: %s\n",banda[i].nome);
        printf("Tipo de musica: %s\n",banda[i].musica);
        printf("Integrantes: %i\n",banda[i].integrantes);
        printf("Posicao: %i\n",banda[i].ranking);
    }
}

int main(){
    Banda banda[TAM];
    /////////////////
    ler(banda);
    mostrar(banda);
    return 0;
}

I left a mark in the places where I made the correction.

    
15.03.2016 / 20:45