如何从用户获取字符串然后动态分配它?

时间:2016-05-06 14:25:18

标签: c

我知道我能做到

char string[100];
gets(string);

但是如何动态地将内存分配给该字符串,该字符串可能不一定是100长度?

1 个答案:

答案 0 :(得分:0)

您可以使用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;
}
相关问题