如何在C中获取未知长度的char*?

nam*_*mco -1 c string pointers

我有一个如下的C代码:

char* text;
get(text); //or
scanf("%s",text);
Run Code Online (Sandbox Code Playgroud)

但是我试着把它打破了.因为我没有给出尺寸text.
为什么我没有给出大小text,因为我不知道用户要输入的文本大小.那么,在这种情况下我能做些什么呢?如果我不知道字符串的长度,我该如何阅读文本?

hac*_*cks 7

你可以试试这个

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

注意:永远不要使用gets函数来读取字符串.它不再存在于标准C.