printf(),参数列表不完整

时间:2014-08-05 10:36:33

标签: c

我正在解决C编程问题而且我遇到了这个

#include<stdio.h>
int main()
{
   int x=100,y=200,z=300;
   printf("%d..%d..%d");
}

我预计会出错,但输出为300..200..100

任何人都可以解释这个输出吗?

4 个答案:

答案 0 :(得分:2)

%d中的

printf期望int类型参数。你没有传递任何论据。它违反约束条件,最终您的程序会调用未定义的行为

答案 1 :(得分:1)

你的代码有很多警告说..

root@jeegar:~/test# gcc -Wall testprintf.c 
testprintf.c: In function ‘main’:
testprintf.c:5:4: warning: too few arguments for format
testprintf.c:4:20: warning: unused variable ‘z’
testprintf.c:4:14: warning: unused variable ‘y’
testprintf.c:4:8: warning: unused variable ‘x’
testprintf.c:6:1: warning: control reaches end of non-void function

当我运行你的代码时,它每次都显示不同的结果。

root@jeegar:~/test# ./a.out 
1822880072..1822880088..4195632root@jeegar:~/test# 
root@jeegar:~/test# 
root@jeegar:~/test# ./a.out 
-1388515512..-1388515496..4195632root@jeegar:~/test# 
root@jeegar:~/test# 
root@jeegar:~/test# 
root@jeegar:~/test# ./a.out 
401499528..401499544..4195632root@jeegar:~/test# 

所以这里有未定义的行为

未定义的行为可能与您的行为产生相同的价值

答案 2 :(得分:0)

当你使用“%d”时,你会说整数输入应该去那里,但你永远不会提供要使用的整数。您需要在字符串后面添加整数作为参数,如下所示:

#include<stdio.h>
int main()
{
   int x=100,y=200,z=300;
   printf("%d..%d..%d", x, y, z);
}

如果你运行printf("%d..%d..%d");,你仍会得到一个输出,但它会是一些随机未初始化的值。

答案 3 :(得分:0)

printf是

int printf(const char*, ...)

具有可变数量参数的函数。 printf使用const char字符串标识参数的数量 - 它计算%符号的数量。它在const char参数之后需要第一个参数并向下遍历堆栈。偶尔会发生局部变量位于功能框架下面。但是在其他编译器和其他指令上,您将获得其他结果,因为在这种情况下,行为是未定义的。例如,在我的计算机上,我得到0,100,200。在获胜VSE时,我在调试模式下获得0..0..random数字并且rand .. 0 .. rand在发布模式等等。