施展 武汉光电国家研究中心 & 计算机学院 华中科技大学
结构是一组相关联的数据集合,成员类型可以不同。
struct stu { char name[20]; float score; };
struct point { int x; int y; }; int main() { struct point a, b; scanf("%d%d%d%d", &a.x, &a.y, &b.x, &b.y); double dx = b.x - a.x; double dy = b.y - a.y; double d = sqrt(dx*dx + dy*dy); printf("distance: %f\n", d); }
double distance(struct point a1, struct point a2) { double dx = a2.x - a1.x; double dy = a2.y - a1.y; return sqrt(dx*dx + dy*dy); }
double distance(struct point *p1, struct point *p2) { double dx = p2->x - p1->x; double dy = p2->y - p1->y; return sqrt(dx*dx + dy*dy); }
struct point a = {1, 2}, b; b = a; // 合法 b = (struct point){3, 5}; // C99复合文字
struct student { char name[20]; int score; }; struct student class[30];
struct student class[3] = { {"Alice", 90}, {"Bob", 85}, {"Charlie", 78} };
stu[0].timeofenter.year
typedef struct { long code; char name[20]; float price; } GOODS; void sort(GOODS *p, int n, int (*cmp)(const void*, const void*));
int cmpbyPrice(const void* s, const void* t) { const GOODS *p1 = (const GOODS*)s; const GOODS *p2 = (const GOODS*)t; return p1->price < p2->price; }
联合所有成员共享同一段内存。
union data { char c; short h; long l; } v = {'A'};
int checkCPUendian() { union { unsigned int a; unsigned char b; } c; c.a = 1; return (c.b == 1); }
union { short n; char bytes[2]; } test; test.n = 0x1234; // test.bytes[0] = 0x34 // test.bytes[1] = 0x12
struct date { unsigned short year : 7; unsigned short month : 4; unsigned short day : 5; };
graph TD A[16位整型] --> B[0-4: day] A --> C[5-8: month] A --> D[9-15: year]
graph TD A[short i] --> B[union] B --> C[struct w16_bytes] B --> D[struct w16_bits] C --> C1[byte0] C --> C2[byte1] D --> D0[b0] --> D15[b15]
struct intNode { int data; struct intNode* next; };
graph LR A[head] --> B[Node1] --> C[Node2] --> D[NULL]
struct intNode* createList() { struct intNode *head = NULL, *tail = NULL; int x; scanf("%d", &x); if (x) { head = tail = malloc(sizeof(struct intNode)); head->data = x; while (scanf("%d", &x), x) { tail->next = malloc(sizeof(struct intNode)); tail = tail->next; tail->data = x; } tail->next = NULL; } return head; }
void printList(struct intNode* head) { while (head) { printf("%d ", head->data); head = head->next; } }
graph LR A[last] --> B[new] --> C[p]
graph LR A[last] --> B[p] --> C[next] A --> C
void sortList(struct intNode* head) { for (struct intNode* p1 = head; p1; p1 = p1->next) for (struct intNode* p2 = p1->next; p2; p2 = p2->next) if (p1->data > p2->data) { int t = p1->data; p1->data = p2->data; p2->data = t; } }
graph LR A[Node1] <--> B[Node2] <--> C[Node3]
graph TD A[学生1] --> B[成绩1] A --> C[成绩2] D[学生2] --> E[成绩1] D --> F[成绩3]