如何解决在C语言中使用指针时出现的分段错误问题?

huangapple go评论56阅读模式
英文:

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&lt;stdio.h&gt;
void main(){
    float p1,p2;
    float *x,*y;
    printf(&quot;Enter the co-ordinates (x,y) : &quot;);
    scanf(&quot;%f%f&quot;,p1,p2);
    x = &amp;p1;
    y = &amp;p2;
    printf(&quot;The co-ordinates(%f,%f) lies in quadrant &quot;,*(x),*(y));
    if(*x == 0 &amp;&amp; *y ==0) {
        printf(&quot;It is the origin.&quot;);
        return;
    }
    if(*x &gt; 0 &amp;&amp; *y &gt; 0){
        printf(&quot;1&quot;);
    }
    else if(*x &lt; 0 &amp;&amp; *y &gt; 0){
        printf(&quot;2&quot;);
    }
    else if(*x &lt; 0 &amp;&amp; *y &lt; 0){
        printf(&quot;3&quot;);
    }
    else printf(&quot;4&quot;);
    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(&quot;%f%f&quot;,p1,p2);

is wrong. %f in scanf() expects pointers of float variable, so it should be

scanf(&quot;%f%f&quot;,&amp;p1,&amp;p2);

Checking for input failure is better.

if (scanf(&quot;%f%f&quot;,&amp;p1,&amp;p2) != 2){
    puts(&quot;failed to read values&quot;);
    return;
}

huangapple
  • 本文由 发表于 2023年3月3日 22:58:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75628633.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定