C error 错误
错误
即使是经验丰富的 C 开发人员也会犯错。关键在于学习如何发现并修复它们!
这些页面涵盖了常见错误和有用的调试技巧,帮助您了解问题所在以及如何修复它。
常见编译时错误
编译时错误是指导致程序无法编译的错误。
1) 缺少分号:
示例
#include <stdio.h>
int main() {
int x = 5
printf("%d", x);
return 0;
}
结果:
error: expected ',' or ';' before 'printf'
2) 使用未声明的变量:
示例
#include <stdio.h>
int main() {
printf("%d", myVar);
return 0;
}
结果:
error: 'myVar' undeclared
3) 类型不匹配(例如,将字符串赋值给整数):
示例
#include <stdio.h>
int main() {
int x = "Hello";
return 0;
}
结果:
错误:初始化时未进行类型转换,指针被初始化为整数
常见运行时错误
运行时错误是指程序编译通过但崩溃或运行异常的情况。
1) 除以零:
示例
#include <stdio.h>
int main() {
int x = 10;
int y = 0;
int result = x / y;
printf("%d\n", result); // not possible
return 0;
}
2) 访问数组越界元素:
示例
#include <stdio.h>
int main() {
int numbers[3] = {1, 2, 3};
printf("%d\n", numbers[8]); // 元素不存在
return 0;
}
3) Using freed memory:
示例
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr = malloc(sizeof(int));
*ptr = 10;
free(ptr);
printf("%d\n", *ptr); // 未定义行为——访问已被释放的内存
return 0;
}
避免错误的良好习惯
- 始终初始化变量
- 使用有意义的变量名
- 保持代码简洁,并使用缩进来保持代码条理清晰
- 保持函数简短且功能明确
- 检查循环或条件语句是否按预期运行
- 仔细阅读错误信息——它们通常会准确地告诉你问题所在
在下一章中,你将学习如何调试代码——如何查找和修复 C 程序中的错误。

