英文:
How to resolve the segmentation fault issue while working with pointers in c?
问题
#include<stdio.h>
void main(){
    float p1, p2;
    float *x, *y;
    printf("输入坐标 (x, y):");
    scanf("%f%f", &p1, &p2);
    x = &p1;
    y = &p2;
    printf("坐标(%f,%f)位于象限 ", *x, *y);
    if (*x == 0 && *y == 0) {
        printf("它是原点。");
        return;
    }
    if (*x > 0 && *y > 0) {
        printf("1");
    }
    else if (*x < 0 && *y > 0) {
        printf("2");
    }
    else if (*x < 0 && *y < 0) {
        printf("3");
    }
    else printf("4");
    return;
}
英文:
#include<stdio.h>
void 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));
    if(*x == 0 && *y ==0) {
        printf("It is the origin.");
        return;
    }
    if(*x > 0 && *y > 0){
        printf("1");
    }
    else if(*x < 0 && *y > 0){
        printf("2");
    }
    else if(*x < 0 && *y < 0){
        printf("3");
    }
    else printf("4");
    return ;
}
This code is throwing an error "Segmentation Fault".
can anyone help me out ?
I have tried to assign values to normal variables then pointers are assigned to that variable's address.But yet it is throwing the same error.
答案1
得分: 3
以下是要翻译的内容:
The line
scanf("%f%f", p1, p2);
is wrong. %f in scanf() expects pointers of float variable, so it should be
scanf("%f%f", &p1, &p2);
Checking for input failure is better.
if (scanf("%f%f", &p1, &p2) != 2){
    puts("failed to read values");
    return;
}
英文:
The line
scanf("%f%f",p1,p2);
is wrong. %f in scanf() expects pointers of float variable, so it should be
scanf("%f%f",&p1,&p2);
Checking for input failure is better.
if (scanf("%f%f",&p1,&p2) != 2){
    puts("failed to read values");
    return;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论