Search code examples
cstructpass-by-value

Error initializing structures with helper function


#include <stdio.h>
 int j=0;

struct student
{
int CNE;
char Nom[20];
char Prenom[20];
char Ville[20];
float Note[3];
float Moyenne;
};

void read_struct(struct student stu)
{   
    stu.Moyenne=0;
    printf("Nom de l'etudiant:\t ");
    scanf(" %s",stu.Nom);
    printf("Prenom de l'etudiant:\t ");
    scanf(" %s",stu.Prenom);
    printf("CNE de l'etudiant:\t ");
    scanf("%d",&stu.CNE);

  }

 int main()
{   
struct student stu[10];
read_struct(stu[0]);
read_struct(stu[1]);
printf("%s \n %s \n",stu[0].Nom,stu[1].Nom);
printf("%d \n %d",stu[0].CNE,stu[1].CNE);

}

I m getting some weird output after compiling, the input from users are not saved in struct after calling them back.( sorry for my english)


Solution

  • Look at how this function is defined:

    void read_struct(struct student stu) {
        ...
    }
    

    When you call this function, it passes in a copy of the struct student, so the function does its work to fill in the copy rather than the original.

    You may want to have this function take in a pointer to the struct student:

    void read_struct(struct student* stu) {
        /* You'll need to change things here */
    }
    
    read_student(&stu[0]);
    read_student(&stu[1]);
    

    Hope this helps!