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
不是指向任何东西的指针。然后,您在分配给每个字段时尝试取消引用该指针。取消引用未初始化的指针会调用未定义的行为。
其次,这不是你想的那样:
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
}
}
推荐阅读
- python - Django url重定向不起作用
- testing - 如何定义用于 Oculus 远程监视器的“远程变量”?
- javascript - Javascript后置摄像头
- android - 滚动时 Listview 中的 Android 项目重叠
- java - 使用 JsonSubTypes 的 InvalidSchemaException,没有选择我在基本接口中定义的内容
- mysql - Mysql where 子句在主键字段上接受带有字符串的整数
- hive - 如何将字符串格式的日期(“April 25, 2018”)转换为 hive 中的时间戳?
- php - 在 PHP 中从 REST API 读取 JSON - 无数据
- angular - 在 Angular 6 中从控制台隐藏 IE 警告
- javascript - 元素句柄的 Puppeteer 循环不起作用