Search code examples
cstructure

Bug right after entering all the data.


I'm writing a little program in C to record a person last name, given name, and age. I'm trying to use structures to do it As soon as I add the age it bugs.

I've tried to use fscanf fgets etc.. but no luck

#include <stdio.h>
#include <printf.h>
#include "personne.h"


int main() {


    Pers user1;

    printf("What's your given name ?");
    scanf("%s",user1.givenname);
    printf("What's your last name ?");
    scanf("%s",user1.lastname);
    printf("What's your age ?");
    scanf("%d",user1.age);

    printf("Your name is %s %s and you're %d years old",user1.givenname,user1.lastname,user1.age);


    return 0;
}


======================================================================

Here's my header file

#ifndef TABLEAU_DE_TYPEPERSONNE_PERSONNE_H
#define TABLEAU_DE_TYPEPERSONNE_PERSONNE_H

#endif //TABLEAU_DE_TYPEPERSONNE_PERSONNE_H


typedef struct Personne Pers;

struct Personne{
    int age;
    char lastname[100];
    char givenname[100];
    char address[1000];


};

normally at the end, it should print the infos.


Solution

  • For scanf to fill the value correctly the address of that value has to be passed to the function, in case of your example, all names are arrays so when you pass their name, you are passing the pointer, but age field is not an array, so you should pass the address with & operator, so just change to this.

    scanf("%d", &user1.age)