在C语言中,可以使用动态内存分配函数`malloc()`和`realloc()`来输入未知长度的字符串。以下是一个示例代码:
```c
include include int main() { char *input = (char *)malloc(100); // 初始分配100个字节的内存空间 char *temp; int len = 0; if (input == NULL) { printf("内存分配失败\n"); return 1; } printf("请输入字符串:\n"); while (1) { if (len >= 100) { // 调整内存空间大小 temp = (char *)realloc(input, len + 10); if (temp == NULL) { printf("内存分配失败\n"); free(input); return 1; } else { input = temp; } } input[len] = getchar(); if (input[len] == '\n') { input[len] = '\0'; break; } len++; } printf("输入的字符串是: %s\n", input); printf("字符串长度为: %d\n", len); free(input); // 释放分配的内存 return 0; } ``` 代码解释: 使用`malloc(100)`分配100字节的内存空间来存储字符串。 使用`while (1)`循环不断读取字符,直到遇到换行符`\n`。 如果当前分配的内存空间不足(即`len >= 100`),则使用`realloc`函数增加内存空间。 当遇到换行符`\n`时,将当前字符存入内存,并在其后添加字符串结束符`\0`。 打印输入的字符串及其长度。 在程序结束前,使用`free`函数释放分配的内存空间。 这种方法可以有效地处理任意长度的字符串输入,但需要注意内存管理,避免内存泄漏。内存分配:
循环输入:
内存调整:
字符串结束:
输出结果:
内存释放: