【问题标题】:how to assign memory to a empy string array如何将内存分配给空字符串数组
【发布时间】:2018-12-01 19:09:04
【问题描述】:

我得到一个空字符串数组,大小为1(自动为1,我真的不知道为什么)

我想为那个空字符串数组分配一个 10 的大小,但我不知道怎么做?

这是我目前的代码

char empty_string_array[] = "";

printf("Enter some strings: eg. asdfjklo...: ");
scanf("%s", &empty_string_array[0]);

int len_of_string = strlen(empty_string_array);
printf("%d\n", len_of_string);

输入:输入一些字符串...:a 输出:字符串的当前长度:1

重启 输入:输入一些字符串......:ab *检测到堆栈粉碎*中止(核心转储)

我想这意味着,没有为多个字符串分配内存,除了已经存在的那个

我知道我可以使用:char empty_string_array[11] = "";对于 10 个字符串和 \0 ,但这并不是最好的解决方案

【问题讨论】:

  • char empty_string_array[11] = ""; for 10 strings and the \0 ,, but this isnt really the best solution 为什么?
  • 因为每个人都一直告诉我,我应该使用 malloc 并分配内存而不是使用缓冲区
  • 我不确定你是否应该听“每个人”的声音;最好找一本好书来学习。
  • 一本好书,就像在干草丛中找针一样:)
  • 但你可能是对的!

标签: c arrays string malloc buffer


【解决方案1】:

既然你必须使用malloc() 那么

char *empty_string_array = (char *)malloc(sizeof(char) * 10 + 1);
//casting from (void *) is not really necessary, though    

printf("Enter some strings: eg. asdfjklo...: ");
scanf("10%s", empty_string_array);

int len_of_string = strlen(empty_string_array);
*(empty_string_array+len_of_string) = '\0';
//or: empty_string_array[len_of_string] = '\0';  your pick
printf("%d\n", len_of_string);

【讨论】:

  • “不过,从 (void *) 进行转换并不是必须的”。不仅没有必要,强烈建议不要这样做。如果您忘记包含 stdlib.h,强制转换它会隐藏发生的错误
  • @FredK:如果你忘记包含<stdlib.h>,你肯定会得到一个malloc()未声明的错误——你永远不会在没有选项的情况下编译,对吗?
猜你喜欢
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-09
相关资源
最近更新 更多