警告:格式为“%d”,预期类型为“ int *”,但参数2的类型为“ int” [英] warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’

查看:163
本文介绍了警告:格式为“%d”,预期类型为“ int *”,但参数2的类型为“ 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\n");
  scanf("%s\n", name);
  printf("input your age\n");
  scanf("%d\n", age);
  printf("%s %d\n", name, age);

}


推荐答案

code> scanf 函数将变量的地址放入结果中。

编写 scanf( %d, & someVar)将通过 someVar <的地址 / code>变量(使用& 一元运算符)。

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 变量的 value 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

您还需要为 scanf 将字符串读入名称

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

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

这篇关于警告:格式为“%d”,预期类型为“ int *”,但参数2的类型为“ int”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆