警告:格式“%d"需要类型“int *",但参数 2 的类型为“int" [英] warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’
问题描述
所以我是 C 的新手,并且对这个警告发生的事情有疑问.警告是什么意思,我该如何解决.我写的代码在这里:
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);
}
推荐答案
scanf
函数将变量的地址 放入其中.
编写 scanf("%d", &someVar)
将传递 someVar 的 address
变量(使用 &
一元运算符).scanf
函数会将一个数字放入该地址的内存中.(其中包含您的变量)
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)
当你写scanf("%d", age)
时,你将age
变量的值传递给scanf代码>.它会尝试将一个数字放入地址
0
的内存块中(因为 age
是 0
),然后一团糟.
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.
您需要将 &age
传递给 scanf
.
You need to pass &age
to scanf
.
您还需要为 scanf
分配内存以将字符串读入 name
:
You also need to allocate memory for scanf
to read a string into name
:
char name[100];
scanf("%99s
", name);
这篇关于警告:格式“%d"需要类型“int *",但参数 2 的类型为“int"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!