Reputation: 11
I am having trouble with the scanf()
function. When I compile and run this code
int ID;
char* name = NULL;
char sex;
float quiz1;
float quiz2;
float midscore;
float finalscore;
float totalscore;
printf("please enter the student information.\n");
printf("ID: ");
scanf("%i", &ID);
printf("Name: ");
scanf(" %s", name);
printf("Sex: ");
scanf(" %c", &sex);
printf("Quiz mark(first semester): ");
scanf(" %f", &quiz1);
printf("Quiz mark(second semester): ");
scanf(" %f", &quiz2);
printf("Mid-term score: ");
scanf(" %f", &midscore);
printf("Final score: ");
scanf(" %f", &finalscore);
printf("Total score: ");
scanf(" %f", &totalscore);
What I get is :
ID: 5
Name: alex
Sex: Quiz mark(first semester): Quiz mark(second semester): Mid-term score: Final score: Total score:
Can someone explain me what's going on?
Upvotes: 0
Views: 213
Reputation: 1006
Here is the problem:
char* name = NULL;
You need to assign some memory to the pointer before writing any data. You can either assign some space statically or dynamically:
char name[10];
char *name2;
name2 = malloc(10*sizeof(char));
Upvotes: 0
Reputation: 134286
At the point of
scanf(" %s", name);
name
is NULL (i.e., it points to invalid memory location), and using that as the argument to %s
invokes undefined behavior.
You need to allocate memory to name
before you can use that to hold the input.
Upvotes: 2