如何解决C语言指针使用中的Segmentation Fault(段错误)问题?
段错误原因分析与修复方案
核心错误原因
scanf("%f%f",p1,p2);这一行是问题根源:使用scanf读取浮点型变量时,必须传递变量的内存地址,但你直接传入了p1、p2的变量值。这会导致scanf试图将输入数据写入一个非法的内存地址,直接触发Segmentation Fault。
修复后的完整代码
#include <stdio.h> #include <math.h> // 用于浮点数绝对值判断 int main(){ float p1,p2; float *x,*y; printf("Enter the co-ordinates (x,y) : "); scanf("%f%f", &p1, &p2); // 修正:传递变量地址 x = &p1; y = &p2; printf("The co-ordinates(%f,%f) lies in quadrant ", *(x), *(y)); // 优化:浮点数精度判断,避免直接==0的误差问题 if(fabs(*x) < 1e-6 && fabs(*y) < 1e-6) { printf("It is the origin."); return 0; } if(*x > 1e-6 && *y > 1e-6){ printf("1"); } else if(*x < -1e-6 && *y > 1e-6){ printf("2"); } else if(*x < -1e-6 && *y < -1e-6){ printf("3"); } else printf("4"); return 0; }
额外优化说明
- main函数返回类型:C标准中
main函数的返回类型应为int,而非void,最后要加上return 0;表示程序正常退出。 - 浮点数比较精度:由于浮点数在存储时存在精度误差,直接用
*x == 0判断可能会出现误判。改用判断绝对值小于1e-6(可根据需求调整精度)的方式,能更准确识别接近0的数值。
内容的提问来源于stack exchange,提问作者Arpan S.
相关产品推荐
相关产品推荐

