指向结构体的指针(Pointers to Structures)
#include <stdio.h>
struct Point {
int x;
int y;
};
void printPoint(struct Point *p) {
printf("Point coordinates: (%d, %d)\n", p->x, p->y);
}
int main() {
struct Point p;
struct Point *ptr;
p.x = 10;
p.y = 20;
ptr = &p;
printPoint(ptr);
return 0;
}
在这个例子中,我们定义了一个Point结构体来表示二维平面上的一个点。然后,我们声明一个指向Point结构体的指针ptr,并将其指向结构体变量p。通过指针,我们可以直接访问结构体的成员,并将指针传递给函数以操作结构体。
结构体的自引用(Self-referential Structures)
#include <stdio.h>
struct Node {
int data;
struct Node *next;
};
int main() {
struct Node node1, node2, node3;
node1.data = 10;
node2.data = 20;
node3.data = 30;
node1.next = &node2;
node2.next = &node3;
node3.next = NULL;
struct Node *current = &node1;
while (current != NULL) {
printf("Data: %d\n", current->data);
current = current->next;
}
return 0;
}
这个例子展示了结构体的自引用,其中每个结构体节点包含一个数据成员和一个指向下一个节点的指针。通过链接多个节点,我们可以创建链表的数据结构。
函数指针成员(Function Pointer Members)
#include <stdio.h>
struct MathOperations {
int (*add)(int, int);
int (*subtract)(int, int);
};
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int main() {
struct MathOperations math;
math.add = add;
math.subtract = subtract;
int result1 = math.add(5, 3);
int result2 = math.subtract(10, 4);
printf("Addition result: %d\n", result1);
printf("Subtraction result: %d\n", result2);
return 0;
}
在这个例子中,我们定义了一个MathOperations结构体,其中包含两个函数指针成员,分别用于执行加法和减法操作。我们将这些函数指针与相应的函数进行关联,并使用结构体中的函数指针调用函数。
动态分配结构体(Dynamic Allocation of Structures)
#include <stdio.h>
#include <stdlib.h>
struct Person {
char name[20];
int age;
};
int main() {
struct Person *person = (struct Person*) malloc(sizeof(struct Person));
if (person == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
strcpy(person->name, "John Doe");
person->age = 25;
printf("Name: %s\n", person->name);
printf("Age: %d\n", person->age);
free(person);
return 0;
}
在这个例子中,我们使用`malloc`函数动态地分配了一个`Person`结构体的内存空间。通过`sizeof`运算符确定所需的内存大小。然后,我们可以像使用普通结构体一样,访问和操作这个动态分配的结构体。最后,记得使用`free`函数释放动态分配的内存空间,以避免内存泄漏。
|