题解 | 牛牛学说话之-字符串

牛牛学说话之-字符串

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;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 12:18
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务