题解 | 牛牛学说话之-字符串
牛牛学说话之-字符串
https://www.nowcoder.com/practice/fa8bde2f612749c9813262a146488c9d
#include <stdio.h>
#include <stdlib.h>
int main() {
int capacity = 10; // 初始缓冲区容量
int len = 0; // 当前字符串长度
char *s = (char *)malloc(capacity * sizeof(char)); // 分配初始内存
if (s == NULL) {
fprintf(stderr, "内存分配失败\n");
return 1;
}
int c;
// 逐个字符读取输入,直到换行符或EOF
while ((c = getchar()) != '\n' && c != EOF) {
// 检查是否需要扩展内存
if (len + 1 >= capacity) {
capacity *= 2; // 双倍扩容
char *temp = (char *)realloc(s, capacity * sizeof(char));
if (temp == NULL) {
fprintf(stderr, "内存分配失败\n");
free(s);
return 1;
}
s = temp;
}
s[len++] = (char)c; // 存储字符并增加长度
}
s[len] = '\0'; // 添加字符串终止符
printf("%s", s); // 输出字符串
free(s); // 释放分配的内存
return 0;
}
查看16道真题和解析
