在C语言中,存储不定长字符串是一项常见且重要的任务,由于C语言本身并不直接支持动态长度的字符串类型,因此需要程序员手动管理内存来存储这些字符串,以下是几种常见的方法来存储不定长字符串:
一、动态内存分配
1、使用malloc
和free
malloc
函数用于分配指定大小的内存块,并返回指向该内存块的指针,在使用完毕后,需要使用free
函数释放先前分配的内存。
示例代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *str; int size; printf("Enter the size of the string: "); scanf("%d", &size); // 使用 malloc 分配内存 str = (char *)malloc(size * sizeof(char)); if (str == NULL) { printf("Memory not allocated. "); return 1; } printf("Enter the string: "); scanf("%s", str); printf("You entered: %s ", str); // 释放内存 free(str); return 0; }
2、使用calloc
calloc
函数类似于malloc
,但它会初始化所分配的内存块为零,这在某些情况下可以避免未初始化内存带来的问题。
示例代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *str; int size; printf("Enter the size of the string: "); scanf("%d", &size); // 使用 calloc 分配内存并初始化为零 str = (char *)calloc(size, sizeof(char)); if (str == NULL) { printf("Memory not allocated. "); return 1; } printf("Enter the string: "); scanf("%s", str); printf("You entered: %s ", str); // 释放内存 free(str); return 0; }
3、使用realloc
realloc
函数用于调整先前分配的内存块大小,这对于处理不定长字符串非常有用,可以在需要时增加或减少内存大小。
示例代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *str; int size; // 初始分配内存 str = (char *)malloc(10 * sizeof(char)); if (str == NULL) { printf("Memory not allocated. "); return 1; } printf("Enter the string: "); scanf("%s", str); printf("You entered: %s ", str); // 调整内存大小 printf("Enter the new size of the string: "); scanf("%d", &size); str = (char *)realloc(str, size * sizeof(char)); if (str == NULL) { printf("Memory not reallocated. "); return 1; } printf("Enter the new string: "); scanf("%s", str); printf("You entered: %s ", str); // 释放内存 free(str); return 0; }
二、使用字符指针数组
1、基本示例
每个指针可以指向一个动态分配的字符串,这种方法适用于存储多个不定长字符串的情况。
示例代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *strArray[5]; int i; for (i = 0; i < 5; i++) { strArray[i] = (char *)malloc(100 * sizeof(char)); if (strArray[i] == NULL) { printf("Memory not allocated. "); return 1; } printf("Enter string %d: ", i + 1); scanf("%s", strArray[i]); } printf("You entered: "); for (i = 0; i < 5; i++) { printf("%s ", strArray[i]); free(strArray[i]); } return 0; }
三、使用链表
1、定义链表节点
首先需要定义一个链表节点结构,每个节点包含一个字符和指向下一个节点的指针。
示例代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Node { char data; struct Node *next; } Node; // 函数用于创建新节点 Node* createNode(char data) { Node *newNode = (Node *)malloc(sizeof(Node)); if (newNode == NULL) { printf("Memory allocation failed. "); return NULL; } newNode->data = data; newNode->next = NULL; return newNode; } // 函数用于释放链表 void freeList(Node *head) { Node *temp; while (head != NULL) { temp = head; head = head->next; free(temp); } }
在C语言中存储不定长字符串有多种方法,每种方法都有其优点和适用场景,动态内存分配是最灵活和常用的方法,但需要注意及时释放内存以避免内存泄漏,字符指针数组和链表则提供了不同的数据结构来存储多个不定长字符串。