Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

c - warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’

So I'm new to C and am having trouble with whats happening with this warning. What does the warning mean and how can i fix it. The code i wrote is here:

void main(void)
{
  char* name = "";
  int age = 0;
  printf("input your name
");
  scanf("%s
", name);
  printf("input your age
");
  scanf("%d
", age);
  printf("%s %d
", name, age);

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The scanf function takes the address of a variable to put the result into.
Writing scanf("%d", &someVar) will pass the address of the someVar variable (using the & unary operator).
The scanf function will drop a number into the piece of memory at that address. (which contains your variable)

When you write scanf("%d", age), you pass the value of the age variable to scanf. It will try to drop a number into the piece of memory at address 0 (since age is 0), and get horribly messed up.

You need to pass &age to scanf.

You also need to allocate memory for scanf to read a string into name:

char name[100];
scanf("%99s
", name);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...