c#include int main() { // 字符数组存储字符串 char str_array[] = "Hello, C Programming!"; // 输出字符串 printf("String stored in array: %s%", str_array); return 0;}
在上述示例中,我们创建了一个字符数组`str_array`,并将字符串"Hello, C Programming!"存储在其中。使用`printf`函数可以轻松地输出该字符串。### 字符串链表存储除了字符数组,我们还可以使用链表来存储字符串。链表是一种动态数据结构,允许我们在运行时动态添加或删除元素。下面是一个简单的例子,展示了如何使用链表存储字符串:
c#include #include #include // 定义字符串节点结构struct Node { char data[50]; struct Node* next;};int main() { // 创建字符串链表 struct Node* head = NULL; struct Node* second = NULL; struct Node* third = NULL; head = (struct Node*)malloc(sizeof(struct Node)); second = (struct Node*)malloc(sizeof(struct Node)); third = (struct Node*)malloc(sizeof(struct Node)); // 分配字符串到节点 strcpy(head->data, "Hello"); strcpy(second->data, "C"); strcpy(third->data, "Programming"); // 链接节点 head->next = second; second->next = third; third->next = NULL; // 遍历并输出链表中的字符串 struct Node* current = head; while (current != NULL) { printf("String stored in linked list: %s%", current->data); current = current->next; } // 释放链表节点的内存 free(head); free(second); free(third); return 0;}