struct.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. typedef struct point { int x,y; } point;
  2. typedef struct rect { point pt1, pt2; } rect;
  3. point addpoint(point p1, point p2) { /* add two points */
  4. p1.x += p2.x;
  5. p1.y += p2.y;
  6. return p1;
  7. }
  8. #define min(a, b) ((a) < (b) ? (a) : (b))
  9. #define max(a, b) ((a) > (b) ? (a) : (b))
  10. rect canonrect(rect r) { /* canonicalize rectangle coordinates */
  11. rect temp;
  12. temp.pt1.x = min(r.pt1.x, r.pt2.x);
  13. temp.pt1.y = min(r.pt1.y, r.pt2.y);
  14. temp.pt2.x = max(r.pt1.x, r.pt2.x);
  15. temp.pt2.y = max(r.pt1.y, r.pt2.y);
  16. return temp;
  17. }
  18. point makepoint(int x, int y) { /* make a point from x and y components */
  19. point p;
  20. p.x = x;
  21. p.y = y;
  22. return p;
  23. }
  24. rect makerect(point p1, point p2) { /* make a rectangle from two points */
  25. rect r;
  26. r.pt1 = p1;
  27. r.pt2 = p2;
  28. return canonrect(r);
  29. }
  30. int ptinrect(point p, rect r) { /* is p in r? */
  31. return p.x >= r.pt1.x && p.x < r.pt2.x
  32. && p.y >= r.pt1.y && p.y < r.pt2.y;
  33. }
  34. struct odd {char a[3]; } y = {'a', 'b', 0};
  35. odd(struct odd y) {
  36. struct odd x = y;
  37. printf("%s\n", x.a);
  38. }
  39. main() {
  40. int i;
  41. point x, origin = { 0, 0 }, maxpt = { 320, 320 };
  42. point pts[] = { -1, -1, 1, 1, 20, 300, 500, 400 };
  43. rect screen = makerect(addpoint(maxpt, makepoint(-10, -10)),
  44. addpoint(origin, makepoint(10, 10)));
  45. for (i = 0; i < sizeof pts/sizeof pts[0]; i++) {
  46. printf("(%d,%d) is ", pts[i].x,
  47. (x = makepoint(pts[i].x, pts[i].y)).y);
  48. if (ptinrect(x, screen) == 0)
  49. printf("not ");
  50. printf("within [%d,%d; %d,%d]\n", screen.pt1.x, screen.pt1.y,
  51. screen.pt2.x, screen.pt2.y);
  52. }
  53. odd(y);
  54. exit(0);
  55. }