【问题标题】:C : Increase Dynamic Array by one in a loopC : 循环增加动态数组
【发布时间】:2013-12-09 13:19:38
【问题描述】:

我想知道为什么我无法在 while 循环中仅将数组大小增加一个。 这是我的代码:

void pb_memory(void){
    printf("ERROR : memory problem !\n");
    system("PAUSE");
    exit(EXIT_FAILURE);
}

int main(int argc, char *argv[])
{
             int length = 0;
            /*allocate memory and check for no error*/
            int *array = calloc(1, sizeof(int)); /*initialize to 0*/
            if(array == NULL)
                     pb_memory();

            /*Check for valid inputs and put into array*/
            while((scanf("%d", &num)) != EOF){
                               array[length]=num;
                               length++;
                               array = realloc(array, length*sizeof(int));
                               if(array == NULL)
                                        pb_memory();
            }
.
.
.
.

}

为什么这不起作用?它失败并直接进入 pb_memory() 函数。我希望每次长度增加一我的数组也这样做......

感谢您的帮助。

编辑:对不起,我想让代码保持简单并专注于我的问题,这就是我没有编写所有变量的原因。无论如何,我正在学习下一次,并感谢@Michael 和所有参与的人。

【问题讨论】:

  • 如何知道初始分配成功?为什么是int *(array) 而不是int *array
  • 尝试声明和初始化length
  • 贴出真实代码(因为这不会编译)
  • 我声明长度 = 0;在我的代码中忘记写回它并且 *(array) 或 *array 不是我认为的问题
  • @Dovakin940,他的意思是这样的sscce.org

标签: c arrays memory-management realloc


【解决方案1】:

您正在尝试访问错误的索引array[length]=num;,如果数组大小为length,则无法访问length-th 元素。

您必须在重新分配后移动写入:

/*Check for valid inputs and put into array*/
while((scanf("%d", &num)) != EOF){
  length++;
  array = realloc(array, length*sizeof(int));
  if(array == NULL)
    pb_memory();
  array[length-1]=num;
}

【讨论】:

  • 不一定是一个错误的答案,但您是如何从 OP 中的错误代码示例中理解这一点的?
  • 这很明显。 length 应该是某个东西的长度(即数组)。
  • @Michael 太棒了,这确实有效,谢谢!
  • @Michael,没有什么是显而易见的。假设是所有“特征”之母。
【解决方案2】:

只是一些想法: 1. 包含一些打印语句以准确查看代码失败的位置 2.运行gdb并输出程序。例如,在 CLI 中,运行命令“gdb ./a.out” 3. 变量“num”在哪里声明?突然出现在while循环的条件下?

【讨论】:

  • 这是评论,不是答案
  • 要发表评论,我需要至少 50 分的声誉,而我没有。所以我不能评论......但我可以回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-15
  • 2021-06-08
  • 1970-01-01
  • 1970-01-01
  • 2015-06-03
  • 2012-08-25
相关资源
最近更新 更多