C 使用防御性编程初始化结构数组时出现问题

C 使用防御性编程初始化结构数组时出现问题,c,C,我需要一些帮助。我正在尝试用感兴趣的点填充结构数组,但我无法将值分配给数组,我需要使用防御性编程来确保这些点位于某些边界内。请帮忙 struct Point_of_Interest { char id[10]; double x; double y; }; struct Point_of_Interest Points[MaxPoints]; void Data_Points(struct Point_of_Interest array[]) { struc

我需要一些帮助。我正在尝试用感兴趣的点填充结构数组,但我无法将值分配给数组,我需要使用防御性编程来确保这些点位于某些边界内。请帮忙

struct Point_of_Interest
{
    char id[10];
    double x;
    double y;
};


struct Point_of_Interest Points[MaxPoints];

void Data_Points(struct Point_of_Interest array[])
{
    struct Point_of_Interest *p;

    int i;
    for(i=0;i<MaxPoints;i++)
    {
        do{
            printf("Give id and coordinates of the city: ");
            scanf("%s",p->id);

            printf("Dwse to X tou %d: ",i+1);
            scanf("%lf",&p->x);

            printf("Dwse to Y tou %d: ",i+1);
            scanf("%lf",&p->y);
        }while(p->x < Xmin && p->y < Ymin && p->x > Xmax && p->y > Ymax);
        array[i]=p->id,&p.x,&p.y;
    }   
}

这里有两个问题。首先,指针
p
不是指向任何东西的指针。然后,在分配给每个字段时,尝试取消引用该指针。取消引用调用的未初始化指针

其次,这并不是在做你认为的事情:

array[i]=p->id,&p.x,&p.y;
这不会将一组值作为一个单元分配给结构。它是一个后跟逗号运算符的赋值

逗号运算符的优先级低于赋值运算符,因此此表达式解析为:

(array[i]=p->id),&p.x,&p.y;
因此,它试图分配
p->id
,这是一个数组到
数组[i]
,这是一个类型不匹配的数组。然后计算并丢弃其他两个值

您可以通过将
p
声明为感兴趣的
struct Point\u的实例而不是指向其中一个的指针来解决这些问题,然后可以将整个结构分配给另一个:

void Data_Points(struct Point_of_Interest array[])
{
    struct Point_of_Interest p;         // not a pointer

    int i;
    for(i=0;i<MaxPoints;i++)
    {
        do{
            // switch from -> to . wherever p is used
            printf("Give id and coordinates of the city: ");
            scanf("%s",p.id);

            printf("Dwse to X tou %d: ",i+1);
            scanf("%lf",&p.x);

            printf("Dwse to Y tou %d: ",i+1);
            scanf("%lf",&p.y);
        }while(p.x < Xmin && p.y < Ymin && p.x > Xmax && p.y > Ymax);
        array[i]=p;    // assign the whole struct
    }   
}
无效数据点(感兴趣的结构点数组[])
{
感兴趣的结构点p;//不是指针
int i;
对于(i=0;i到。无论使用p
printf(“给出城市的id和坐标:”);
scanf(“%s”,p.id);
printf(“Dwse到X头%d:,i+1);
scanf(“%lf”和p.x);
printf(“Dwse到Y tou%d:,i+1);
scanf(“%lf”和p.y);
}而(p.xXmax&&p.y>Ymax);
数组[i]=p;//分配整个结构
}   
}

你需要改变你的状况。假设
xmin
,那么
xxmax
怎么可能是真的?它要么小于最小值,要么大于最大值,但几乎两者都没有。
void Data_Points(struct Point_of_Interest array[])
{
    struct Point_of_Interest p;         // not a pointer

    int i;
    for(i=0;i<MaxPoints;i++)
    {
        do{
            // switch from -> to . wherever p is used
            printf("Give id and coordinates of the city: ");
            scanf("%s",p.id);

            printf("Dwse to X tou %d: ",i+1);
            scanf("%lf",&p.x);

            printf("Dwse to Y tou %d: ",i+1);
            scanf("%lf",&p.y);
        }while(p.x < Xmin && p.y < Ymin && p.x > Xmax && p.y > Ymax);
        array[i]=p;    // assign the whole struct
    }   
}