c - Trying to read an int into a struct, but it returns a segfault? -


so have code reading in strings , applying them respective struct members fine, reading int, program crashes , returns segfault. if assign variable value, pass value struct, works fine. if assign variable value, overwrite value scanf, pass struct, segfaults again.

void createcompetitor() {     struct competitor *newcompetitor = malloc(sizeof (struct competitor));     if (newcompetitor == null)         return;     printf("please enter competitor's first name\n");     fgets(newcompetitor->firstname, 25, stdin);     printf(newcompetitor->firstname);     printf("please enter competitor's last name\n");     fgets(newcompetitor->lastname, 35, stdin);     printf(newcompetitor->lastname);     printf("please enter competitor's address\n");     fgets(newcompetitor->address, 105, stdin);     printf(newcompetitor->address);     printf("please enter competitor's age\n");     scanf("%d", &newcompetitor->phonenumber);     scanf("%c");     printf("%d", newcompetitor->age);     printf("please enter competitor's phone number\n");     scanf("%d", &newcompetitor->phonenumber);     scanf("%c");     printf("%d", newcompetitor->phonenumber);     printf("please enter competitor's registration number\n");     scanf("%d", &newcompetitor->competitornumber);     scanf("%c");     printf("%d", newcompetitor->competitornumber); } 

sorry super messy code, i'm trying figure out going on program.

edit: struct definition

struct competitor {     char firstname[20];     char lastname[30];     char address [100];     int age;     int phonenumber;     int competitornumber;     struct competitor *next; }; 

note mismatch

char firstname[20]; 

and

fgets(newcompetitor->firstname, 25, stdin); 

you allow writing outside of array boundaries, that's undefined behavior.

scanf("%c"); culprit.

scanf reads input stdin , attempts write address passed parameter, didn't pass address!

the behavior of entire program undefined. thankful crashed.

if intend wait user interaction before continuing, specify in format scnaf character should read, not written anywhere. this:

`scanf("%*c");` 

this brittle "waiting user interaction" technique. bear in mind.


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -