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[])
{
    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);

最佳答案

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

第二,这不是你想的那样:

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

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

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

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

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

您可以通过将 p 声明为 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
    }   
}

关于c - 使用防御性编程初始化结构数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54884453/

相关文章:

c - 为什么这个函数会导致段错误?

php - zend_call_method_with_N_params

c - 打印整数值时出现意外输出

检查c中数组中的值

c - 变量只拾取传递字符串的一个字母

c - 统计返回 ENOENT

c - 从 .log 文件读取十六进制数据时出错

c++ - 为什么要先编译成目标文件?

Python 使用 ctypes 传递参数,参数无效

连续字符串