Home > Back-end >  C returning a struct results in gibberish
C returning a struct results in gibberish

Time:12-02

I'm trying to return a struct from a function but trying to print its content in main but all I get is gibberish this is the struct

struct date
{
    int jour;
    int mois;
    int annee;
};
typedef struct date DATE;

struct client
{
    char nom[50];
    char prenom[50];
    char cin[12];
    DATE date_naiss;
    char num_passport[10];
    int a;
};

This is my Main function

void main()
{
    CLIENT clt;
    clt=creer_client();
    afficher_client(clt);
}

This is the function that returns the struct

CLIENT creer_client()
{
    CLIENT clt;
    printf("Donner le nom du client : ");
    fgets(clt.nom, 50, stdin);
    printf("Donner le prenom du client : ");
    fgets(clt.prenom, 50, stdin);
    printf("Donner le CIN du client : ");
    fgets(clt.cin, 12, stdin);
    while (cntrl_cin(clt.cin) == false)
    {
        fgets(clt.cin, 12, stdin);
    }
    printf("donner la date de naissance");
    scanf("%d%d%d", &clt.date_naiss.jour, &clt.date_naiss.mois, &clt.date_naiss.annee);
    getchar();
    printf("donner le numero de passeport : ");
    fgets(clt.num_passport, 10, stdin);
}

And this is the function that prints the struct

void afficher_client(CLIENT clt)
{
    printf("nom: %s \tprenom:%s\ncin:%s\ndate de naissance: %d/%d/%d \nnumero passeport: %s", clt.nom, clt.prenom, clt.cin, clt.date_naiss.jour, clt.date_naiss.mois, clt.date_naiss.annee, clt.num_passport);
}
```

CodePudding user response:

You seem to be missing a return statement:

CLIENT creer_client()
{
    CLIENT clt;
    /* all the stuff you had before */
    return clt; /* <- You were missing this */
}

I am surprised your compiler did not give you a warning or error about this.

  • Related