c - 我怎样才能从用户那里得到一个字符串然后动态分配它?

标签 c

<分区>

我知道我能做到

char string[100];
gets(string);

但我如何才能动态地为该字符串分配内存,该字符串的长度不一定是 100?

最佳答案

您可以使用realloc 来获取未知长度的字符串。逐个字符读取输入的字符串,直到找到'\n'EOF,每次使用realloc为下一个字符分配内存读。

char *read_string(void)
{
    int c;
    int i = 0;
    char *s = malloc(1);
    printf("Enter a string: \t"); // It can be of any length
    /* Read characters until found an EOF or newline character. */
    while((c = getchar()) != '\n' && c != EOF)
    {
        s[i++] = c;
        s = realloc(s, i+1); // Add memory space for another character to be read.
    }
    s[i] = '\0';  // Nul terminate the string
    return s;
}

关于c - 我怎样才能从用户那里得到一个字符串然后动态分配它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37074900/

相关文章:

c - 我对这个 C 程序如何工作的理解正确吗?

c - 哪种排序算法对 c 中具有唯一元素的结构数组快速

c - 替换文件中的字符

c - 像宏这样的功能是什么意思?

c++ - 在 OpenGL 2.1 中使用 glDrawRangeElements

c 使用 malloc 分配内存

goto的C用法

c - 如何在 C 中使用迭代器宏来防止阴影

c - 如何在 C 中使用 getopt 打印帮助文本?

c - 将文本文件中的字符串读入结构时出现段错误