代码在循环的第二次运行中停止

时间:2014-12-13 12:38:22

标签: c pointers data-structures while-loop scanf

我无法运行此代码以便提供两个输入。它在运行时突然停止。代码如下。请帮我修理它。

流程返回-1073741819(0xC0000005) 按任意键继续。是错误消息

#include <stdio.h>
#include<malloc.h>
#include<conio.h>
struct coordinates
{
    int x;
    int y;
    struct coordinates *link;
};
void append(struct coordinates **q,int xx , int yy)
{
    struct coordinates *r,*s;

    if(*q == NULL)
    {
        r = (struct coordinates *)malloc(sizeof(struct coordinates));
        r->x=xx;
        r->y=yy;
        *q=r;
    }

    else
    {
        r=*q;
        while(r->link != NULL)
        r= r->link;

        s=(struct coordinates *)malloc(sizeof(struct coordinates));
        s->x=xx;
        s->y=yy;
        s->link=NULL;

        r->link=s;

    }
}
void display(struct coordinates *temp)
{
    while (temp  != NULL)
    {
        printf("x coordinate is %d ,Y coordinate is %d",temp->x,temp->y);
        temp=temp->link;
    }
}
int main()
{
    struct coordinates *start;
    start=NULL;

    char name;
    int xxx,yyy;

    while(1)
    {
        printf("If you want to continue input loop press y \n");
        scanf(" %c", &name);
        if (name == 'y')
        {
            printf("enter x coordinate of element \n");
            scanf("%d",&xxx);
            printf("%d\n",xxx);

            printf("enter y coordinate of element \n");
            scanf("%d",&yyy);
            printf("%d\n",yyy);

            append(&start,xxx,yyy);

        }
        else
        {
            printf("You have exited input loop \n");
            break;
        }

    }
    display(start);
}

1 个答案:

答案 0 :(得分:3)

成功

r->x = xx;
r->y = yy;
r->link = NULL;

在追加的第一个分支中,否则r->link在第二次列表的末尾有未指定的值(不太可能是NULL)。