我对C编程很陌生并且有一个疑问......我被要求在C代码的某些部分找到错误...而且这段我有点困惑所以会很感激帮助......
int main(void)
{
int myInt = 5;
printf("myInt = %d");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
据我所知,这段代码没有错.我想知道的是为什么这个陈述打印出一个随机数?
我得到的输出是
myInt = 1252057154
Run Code Online (Sandbox Code Playgroud)
非常感谢帮助...谢谢
您应该阅读有关C编程的更多信息.
您应该在编译时启用所有警告和调试.使用GCC,这意味着gcc -Wall -Wextra -g(至少在Linux上).
编译时
gcc -Wall -Wextra -g john.c -o john
Run Code Online (Sandbox Code Playgroud)
我收到以下警告:
john.c: In function ‘main’:
john.c:4:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
john.c:4:5: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
john.c:4:5: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat]
john.c:3:9: warning: unused variable ‘myInt’ [-Wunused-variable]
Run Code Online (Sandbox Code Playgroud)
所以修正很简单:
/* file john.c */
#include <stdio.h>
int main(void)
{
int myInt = 5;
printf("myInt = %d\n", myInt);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在没有警告的情况下编译.
请注意格式字符串\n的末尾printf.这很重要.
始终启用编译器可以提供给您的所有警告并信任编译器,因此请更正代码,直到没有给出警告.
并学会使用调试器(例如gdb在Linux上).
您观察到的行为是未定义的行为 ; 任何事情都可能发生在C的标准符合实施(甚至爆炸).
快乐的黑客.