在C语言中,可以使用指针变量来创建包含指针的原子结构。下面是一个示例代码:
#include
#include
typedef struct {
int data;
struct Node* next;
} Node;
int main() {
Node* node1 = (Node*)malloc(sizeof(Node));
Node* node2 = (Node*)malloc(sizeof(Node));
Node* node3 = (Node*)malloc(sizeof(Node));
node1->data = 1;
node2->data = 2;
node3->data = 3;
node1->next = node2;
node2->next = node3;
node3->next = NULL;
Node* current = node1;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
free(node1);
free(node2);
free(node3);
return 0;
}
在上面的示例中,我们定义了一个包含指针的原子结构Node
,它包含一个整数数据data
和一个指向下一个Node
结构的指针next
。然后,我们动态分配了3个Node
结构的内存,并将它们连接起来形成一个链表。最后,我们使用一个指针变量current
遍历链表,并打印每个节点的数据。
需要注意的是,在使用完指针变量后,我们要记得使用free()
函数释放动态分配的内存,以避免内存泄漏。
上一篇:包含指向另一个对象的指针的对象向量(Vector of objects that contains a pointer to another object)
下一篇:包含指针的“for loop”