C 语言 - 错误
错误
即使是经验丰富的 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) 类型不匹配(例如,将字符串赋值给 int):
实例
#include <stdio.h>
int main() {
int x = "Hello";
return 0;
}
结果:
error: initialization makes integer from pointer without a cast
常见的运行时错误
运行时错误发生在程序编译通过但崩溃或行为异常时。
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]); // element does not exist
return 0;
}
3) 使用已释放的内存:
实例
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr = malloc(sizeof(int));
*ptr = 10;
free(ptr);
printf("%d\n", *ptr); // 未定义行为 - 访问已释放的内存
return 0;
}
避免错误的好习惯
- 始终初始化您的变量
- 使用有意义的变量名
- 保持代码整洁并使用缩进以保持组织性
- 保持函数简短且专注
- 检查循环或条件是否按预期运行
- 仔细阅读错误消息 - 它们通常会准确告诉您问题所在
在下一章中,您将学习如何调试代码 - 如何查找并修复 C 程序中的错误。