在C語言中,結構體嵌套是指在一個結構體內部定義另一個結構體。這種特性可以與C語言的其他特性結合使用,以實現更復雜的數據結構和功能。以下是一些常見的結合方式:
#include <stdio.h>
typedef struct {
int x;
int y;
} Point;
void print_point(Point *p) {
printf("(%d, %d)\n", p->x, p->y);
}
int main() {
Point p = {3, 4};
print_point(&p);
return 0;
}
#include <stdio.h>
typedef struct {
int x;
int y;
} Point;
int main() {
Point points[3] = {{1, 2}, {3, 4}, {5, 6}};
for (int i = 0; i < 3; i++) {
printf("(%d, %d)\n", points[i].x, points[i].y);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *create_node(int data) {
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
int main() {
Node *head = create_node(1);
head->next = create_node(2);
head->next->next = create_node(3);
Node *current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
return 0;
}
#include <stdio.h>
typedef struct {
int type;
union {
int num;
float f;
} data;
} Data;
int main() {
Data d1;
d1.type = 1;
d1.data.num = 42;
printf("Type: %d, Value: %d\n", d1.type, d1.data.num);
Data d2;
d2.type = 2;
d2.data.f = 3.14;
printf("Type: %d, Value: %f\n", d2.type, d2.data.f);
return 0;
}
這些示例展示了如何將結構體嵌套與其他C語言特性結合使用,以實現更復雜的數據結構和功能。