这个值是从哪里来的?
Where did this value come from?
我正在学习C语言的转换说明符部分。我知道 %d 用于在逗号后面打印值,但是,我不明白为什么 printf
在逗号后面没有值时打印一些东西。也没有编译错误。
#include <stdio.h>
int main(void) {
printf("%d");
return 0;
}
结果:
13242433
谁能告诉我为什么我运行这段代码时会出现这个随机数字?
这是未定义的行为。当在 printf
中使用 %d
时,它需要一个 int
.
类型的参数
这是什么?
未定义的行为。(检查ref-1, ref-2)
为什么会这样?
来自标准 7.21.6.1
The fprintf
function writes output to the stream pointed to by stream
,
under control of the string pointed to by format
that specifies how
subsequent arguments are converted for output.If there are
insufficient arguments for the format, the behavior is undefined
如何避免?
编译时也是
gcc -Wall -Wextra -Werror progname.c
给出错误(由于-Werror
)
error: format ‘%d’ expects a matching ‘int’ argument [-Werror=format=]
printf("%d");
^
这很清楚,可以告诉您出了什么问题。但是你没有检查。
那么获取的值是多少?那只是垃圾值吗?
很可能 printf
看到 %d
说明符时试图从内存中读取一个 int
变量的值。但遗憾的是,记忆中没有任何对你有意义的东西。 (甚至可能不允许访问该内存。)是的,它只是一些价值——垃圾价值。甚至不要认为每次你都会得到一些垃圾值——不要依赖它或类似的东西。这是未定义的行为。下次它可能会使您的程序崩溃或只是打印我的联系电话。1,2
1.答案的最后一部分解释了垃圾打印的可能原因。
2。 print my contact number
- 只是指出它只是一个您不应该关心的垃圾值。此外,它是未定义的行为——即使看到垃圾值也不能保证每次都会发生。
好吧,gcc 在编译您的代码时会显示警告:
test.c: In function ‘main’:
test.c:5:12: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=]
printf("%d");
^
我不确定,但如果您使用 Visual Studio,可能会有一些错误。在那种情况下你应该 post 你的问题 here.
我正在学习C语言的转换说明符部分。我知道 %d 用于在逗号后面打印值,但是,我不明白为什么 printf
在逗号后面没有值时打印一些东西。也没有编译错误。
#include <stdio.h>
int main(void) {
printf("%d");
return 0;
}
结果: 13242433
谁能告诉我为什么我运行这段代码时会出现这个随机数字?
这是未定义的行为。当在 printf
中使用 %d
时,它需要一个 int
.
这是什么?
未定义的行为。(检查ref-1, ref-2)
为什么会这样?
来自标准 7.21.6.1
The
fprintf
function writes output to the stream pointed to bystream
, under control of the string pointed to byformat
that specifies how subsequent arguments are converted for output.If there are insufficient arguments for the format, the behavior is undefined
如何避免?
编译时也是
gcc -Wall -Wextra -Werror progname.c
给出错误(由于-Werror
)
error: format ‘%d’ expects a matching ‘int’ argument [-Werror=format=]
printf("%d");
^
这很清楚,可以告诉您出了什么问题。但是你没有检查。
那么获取的值是多少?那只是垃圾值吗?
很可能 printf
看到 %d
说明符时试图从内存中读取一个 int
变量的值。但遗憾的是,记忆中没有任何对你有意义的东西。 (甚至可能不允许访问该内存。)是的,它只是一些价值——垃圾价值。甚至不要认为每次你都会得到一些垃圾值——不要依赖它或类似的东西。这是未定义的行为。下次它可能会使您的程序崩溃或只是打印我的联系电话。1,2
1.答案的最后一部分解释了垃圾打印的可能原因。
2。 print my contact number
- 只是指出它只是一个您不应该关心的垃圾值。此外,它是未定义的行为——即使看到垃圾值也不能保证每次都会发生。
好吧,gcc 在编译您的代码时会显示警告:
test.c: In function ‘main’:
test.c:5:12: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=]
printf("%d");
^
我不确定,但如果您使用 Visual Studio,可能会有一些错误。在那种情况下你应该 post 你的问题 here.