首页 > 解决方案 > 使用防御性编程初始化结构数组的问题

问题描述

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

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;
    }   
}

在主调用内部

Data_Points(Points);

标签: c

解决方案


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

其次,这不是你想的那样:

array[i]=p->id,&p.x,&p.y;

这不会将一组值作为一个单元分配给一个结构。这是一个后跟逗号运算符的赋值。

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

(array[i]=p->id),&p.x,&p.y;

所以它试图分配p->id,这是一个数组array[i],这是一个类型不匹配的。然后评估并丢弃其他两个值。

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

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
    }   
}

推荐阅读