【问题标题】:adding an element to an array using realloc使用 realloc 向数组添加元素
【发布时间】:2013-01-07 23:57:39
【问题描述】:

我正在尝试在输入字符后使用 realloc 将元素添加到数组中。 这是我的代码:

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

   int main(void)
   {
      int i, j, k;
      int a = 1;
      int* array = (int*) malloc(sizeof(int) * a);
      int* temp;
      for(i = 0;;i++)
      {
          scanf("%d", &j);
          temp = realloc(array, (a + 1) * sizeof(int));
          temp[i] = j;
          if(getchar())
            break;
      }
      for(k=0; k <= a; k++)
      {
          printf("%d", temp[k]);
      }
   }

当我运行这个小程序时,如果我输入例如:2 3 4 它显示我:20; 我知道内存没有正确分配,但我无法弄清楚问题所在。 提前致谢。

【问题讨论】:

  • 你似乎从未修改过a...

标签: c malloc realloc


【解决方案1】:

首先:

    int* array = (int*) malloc(sizeof(int) * a);
    int* temp = array;

和

    temp = realloc(temp, (a + 1) * sizeof(int));

因为作为第一个参数传递的调用'realloc'指针可能会变得无效。

当然 'realloc' 调用的第二个参数总是等于 2。

顺便说一句,'scanf' 在第一个非数字字符之后停止读取您的输入字符串。阅读文档以了解正确使用功能。例如关于scanf() 或realloc()。

【讨论】:

  • 我只修复了分配器的错误使用。您的代码包含其他几个错误,例如:使用“scanf”不正确,数组中的第一个元素未定义,但您尝试在最后一个循环中将其取出,等等。
猜你喜欢
  • 2022-01-20
  • 1970-01-01
  • 2014-08-03
  • 1970-01-01
  • 2012-03-23
  • 1970-01-01
  • 1970-01-01
  • 2011-08-11
  • 2015-09-02
相关资源
最近更新 更多