【问题标题】:How to get char* with unknown length in C? [duplicate]如何在C中获得长度未知的char *? [复制]
【发布时间】:2015-06-08 23:05:51
【问题描述】:

我有一个如下的 C 代码:

char* text;
get(text); //or
scanf("%s",text);

但我尝试运行它会中断。因为我没有给出text 的大小。
为什么我没有给出text 的尺寸,因为我不知道尺寸是多少 用户将要输入的文本。 那么,在这种情况下,我该怎么办? 如果我不知道字符串的长度,如何阅读文本?

【问题讨论】:

标签: c string pointers


【解决方案1】:

你可以试试这个

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

注意:切勿使用gets 函数读取字符串。它不再存在于标准 C 中。

【讨论】:

  • char 的大小不取决于架构吗?您使用了 malloc(1) 而不是 malloc(sizeof(char))。
  • @Kumar;如果我记得的话,char 的大小总是1 byte(尽管在每个架构上一个字节不一定是 8 位)。
猜你喜欢
  • 2019-09-02
  • 1970-01-01
  • 2017-03-18
  • 2014-01-28
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 2021-05-06
  • 1970-01-01
相关资源
最近更新 更多