[英]how to solve type redefinition error in this C program
I'm a new C programmer,我是一个新的 C 程序员,
the program I was writing has to return 0 if the points are colinear, otherwise it has to return 1. I've split the code in .h and .c.如果点是共线的,我正在编写的程序必须返回 0,否则它必须返回 1。我已将代码拆分为 .h 和 .c。 This is the code: [geometry.c]
这是代码:[geometry.c]
struct point {
int x;
int y;
} p1;
struct point {
int x;
int y;
} p2;
struct point {
int x;
int y;
} p3;
int colinear(struct point* p1, struct point* p2, struct point* p3) {
if (((p1->x - p2->x)* (p1->y - p2->y) == ((p3->y - p2->y) * (p1->x - p2->x))))
return 0;
else
return 1;
}
and: [geometry.h]和:[几何.h]
#ifndef geometry.h
#define geometry.h
#endif
#include "geometry.c"
extern int colinear(struct point *p1, struct point *p2, struct point *p3);
Using the debugger: "C2011: 'point': 'struct' type redefinition".使用调试器:“C2011: 'point': 'struct' type redefinition”。
Where are the errors?错误在哪里?
No Need to define 3 times不需要定义3次
struct point {
int x;
int y;
} p1;
struct point {
int x;
int y;
} p2;
struct point {
int x;
int y;
} p3;
define only once, and create variables as you wish.只定义一次,并根据需要创建变量。
struct point {
int x;
int y;
};
struct point p1,p2,p3;
The other answer addresses the problem well.另一个答案很好地解决了这个问题。 (ie why the code resulted in multiply defined compiler error.) But as a possible enhancement to your corrected code, the following is a related construct using an array of a
typedef
struct
. (即为什么代码导致多重定义的编译器错误。)但作为对更正代码的可能增强,以下是使用
typedef
struct
数组的相关构造。 This may make some of what you need to do a little easier to pass around and manipulate the struct member values:这可能会使您需要做的一些事情更容易传递和操作结构成员值:
typedef struct {
int x;
int y;
} point_s;
point_s p[3];
This effectively allows the prototype:这有效地允许原型:
int colinear(struct point* p1, struct point* p2, struct point* p3) {
To be refactored into:重构为:
int colinear(point_s *p) { //where p is an pointer to 3 instances of point_s
Usage example:用法示例:
int main(void)
{
point_s p[3] = {{4,6}, {-2, 5}, {-0.4, 15}};
int result = colinear(p);
return 0;
}
int colinear(point_s *p)
{
if (((p[0].x - p[1].x)* (p[0].y - p[1].y) == ((p[2].y - p[1].y) * (p[0].x - p[1].x))))
{
return 0;
}
else
{
return 1;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.