1.结构体struct
1.1 结构体的基本知识
#include <stdio.h>
struct point{
int x;
int y;
}p1, p2, p3;
struct point pt;
struct point pt2 = {300, 400};
struct point pt3 = {.x = 500};
struct rect {
struct point pt1;
struct point pt2;
};
struct rect screen;
int main()
{
printf("pt2.x = %d, pt2.y = %d\n", pt2.x, pt2.y);
printf("pt3.x = %d, pt3.y = %d\n", pt3.x, pt3.y);
double dist, sqrt();
dist = sqrt((double)pt2.x*pt2.x + (double)pt2.y*pt2.y);
printf("dist = %lf \n", dist);
printf("screen.pt2.x = %d \n", screen.pt2.x);
return 0;
}
huashidazhongbeitushuguan5deiMac:wufile duzhe$ vim struct.c
huashidazhongbeitushuguan5deiMac:wufile duzhe$ gcc struct.c
huashidazhongbeitushuguan5deiMac:wufile duzhe$ ./a.out
pt2.x = 300, pt2.y = 400
pt3.x = 500, pt3.y = 0
dist = 500.000000
screen.pt2.x = 0
huashidazhongbeitushuguan5deiMac:wufile duzhe$
1.2 结构体与函数
- 传递结构体的每个成员变量;
- 传递整个机构体;
- 传递指向结构体的指针;
#include <stdio.h>
struct point{int x; int y;};
struct rect {
struct point pt1;
struct point pt2;
};
struct rect screen;
struct point midlle;
struct point makepoint(int, int);
int main()
{
#define XMAX 300
#define YMAX 400
screen.pt1 = makepoint(0, 0);
screen.pt2 = makepoint(XMAX, YMAX);
struct point origin = {30}, *pp;
origin.y = 40;
//origin = {.x = 30, .y = 40}; //error
//origin = {30, 40}; //error
pp = &origin;
printf("origin: .x,.y is (%d, %d)\n", origin.x, origin.y);
printf("origin: (*pp).x is (%d, %d)\n", (*pp).x, (*pp).y);
printf("origin: pp->x is (%d, %d)\n\n", pp->x, pp->y);
return 0;
}
struct point makepoint(int x, int y)
{
struct point temp;
temp.x = x;
temp.y = y;
return temp;
}
/*
struct point addpoint(struct point p1, struct point p2)
{
p1.x += p2.x;
p1.y += p2.y;
return p1;
}
int pt_in_rect(struct point p, struct rect r)
{
return p.x >= r.pt1.x && p.x <= r.pt2.x
&& p.y >= r.pt1.y && p.y <= r.pt2.y;
}
#define min(a,b) ((a) < (b) ? (a) : (b))
#define max(a,b) ((a) > (b) ? (a) : (b))
// 矩形规范化
struct rect canon_rect(struct rect r)
{
struct rect temp;
temp.pt1.x = min(r.pt1.x, r.pt2.x);
temp.pt1.y = min(r.pt1.y, r.pt2.y);
temp.pt2.x = max(r.pt1.x, r.pt2.x);
temp.pt2.y = max(r.pt1.y, r.pt2.y);
return temp;
}
*/
struct rect r, *rp = &