格式'%d'需要'int *'类型的参数,但参数的类型为'int'
问题描述:
if (answer == 'Y') {
int a, u, l;
printf("How many numbers do you need?\n");
scanf("%d", a);
程序在此行后崩溃。我应该用什么来代替“%d”?格式'%d'需要'int *'类型的参数,但参数的类型为'int'
printf("Specify the lower bound of the range:");
scanf("%d", l);
printf("Specify the upper bound of the range:");
scanf("%d", u);
for(c = 1;c <= a ;c++) {
n = rand() %(u - l) + 1;
printf("%d\n", n);
}
}
答
你需要通过变量的地址,因为scanf()
将值存储在它。
该程序崩溃,因为scanf()
取消引用int
这是甚至还没有初始化这两个事情导致未定义的行为。
其实,这些都是不确定的行为,所有发生在单一scanf()
呼叫
- 访问一个空指针
- 传递不正确的类型给定的格式说明。
- 从初始化的变量读。
要通过地址使用操作
if (scanf("%d", &a) == 1) {
// Proceed with `a' and use it
} else {
// Bad input, do not use `a'
}
的&
地址在这种情况下,该警告是不是一个错误,因为int
原则上转换为指针,但如果你的行为是不确定的尝试引用此类型,并且指针大小可能太大而不能存储int
。
这个警告是非常严重的,忽略它不会产生良好的行为,因为它涉及到治疗值,是不太可能,如果它是一个指针值,这通常会导致程序崩溃。
一般而言,如果您知道自己在做什么,只应忽略警告。而且几乎从不,你会有目的地引发警告,尽管在某些情况下它可能是合法的。
作为一个初学者(我知道你只是一个初学者,因为你正在使用scanf()
),你一定不能忽略警告。
而且,即使你的课本例子从来不检查的scanf()
你应该返回值。不这样做,特别是当你还没有初始化变量,但可能会调用未定义的行为。
答
scanf("%d", &a);
scanf()
需要作为参数他可以存储信息的地址。
a
是变量的名称,而&a
是包含该变量的内存地址。如下图所示在scanf可变的
答
通行证地址:
if (answer == 'Y') {
int a, u, l;
printf("How many numbers do you need?\n");
scanf("%d", &a);
printf("Specify the lower bound of the range:");
scanf("%d", &l);
printf("Specify the upper bound of the range:");
scanf("%d", &u);
for(int c = 1;c <= a ;c++) {
n = rand() %(u - l) + l;
printf("%d\n", n);
}
}
上使用'scanf的任何C教程()'应该解释清楚。 – Barmar