Reputation: 541
I'm a new C programmer,
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. This is the code: [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]
#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".
Where are the errors?
Upvotes: 1
Views: 1697
Reputation: 23218
The other answer addresses the problem well. (i.e. 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
. 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;
}
}
Upvotes: 0
Reputation: 1738
No Need to define 3 times
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;
Upvotes: 3