c - 分配一个未知大小的数组

标签 c arrays dynamic

上下文:我想做的是制作一个程序,它将文本作为输入并将其存储在字符数组中。然后我将数组的每个元素打印为小数。例如。 “Hello World”将被转换为 72、101 等。我会将其用作快速 ASCII2DEC 转换器。我知道有在线转换器,但我想自己制作一个。

问题:如何分配一个在编译时大小未知的数组,并使其与我输入的文本大小完全相同?因此,当我输入“Hello World”时,它会动态生成一个数组,其大小恰好只需要存储“Hello World”。我在网上搜索过,但找不到任何我可以使用的东西。

最佳答案

我看到您使用的是 C。您可以这样做:

 #define INC_SIZE 10

 char *buf = (char*) malloc(INC_SIZE),*temp;
 int size = INC_SIZE,len = 0;
 char c;

 while ((c = getchar()) != '\n') { // I assume you want to read a line of input
   if (len == size) {
     size += INC_SIZE;
     temp = (char*) realloc(buf,size);
     if (temp == NULL) {
       // not enough memory probably, handle it yourself
     }
     buf = temp;
   }
   buf[len++] = c;
 }
 // done, note that the character array has no '\0' terminator and the length is represented by `len` variable

关于c - 分配一个未知大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9963026/

相关文章:

带有构造函数参数的动态Java类

javascript - Jssor 动态缩略图不起作用

c - 用户在 C 中的结构中输入?

c - Pthread Xlib编程

java - 将 switch case 与数组结合使用

java - 将一个 int 和 string 数组合并到第三个数组中

c - matlab 与 C 版本中的 svmtrain 函数执行时间

c - C 中的矩阵乘法多进程

arrays - 构建一个 "sparse"查找数组,最小化内存占用

c++ - 动态内存管理场景