【问题标题】:Unexpected output of a growing dynamic array不断增长的动态数组的意外输出
【发布时间】:2020-12-30 13:15:24
【问题描述】:

我正在尝试创建一个动态数组,如果需要,它的大小会增加,因为我不知道该数组实际上会有多大。我的代码似乎一直有效,直到数组的第 8 个元素开始看到我没有输入的非常大的错误值。不知道为什么会这样。

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

int main (int argc, char** argv)
{
 int val; 
 int userInput; 
 int* arr;  
 int size = 1; 
 int arrIndex = 0; 
 arr = (int*) malloc(sizeof(int) * size);


 /* prompt the user for input */
 printf ("Enter in a list of numbers to be stored in a dynamic array.\n");
 printf ("End the list with the terminal value of -999\n");
 
 /* loop until the user enters -999 */
 scanf ("%d", &val);
 while (val != -999)
   {
     if (arrIndex >= size)

      {
        size++; 
        
      }

    arr[arrIndex] = val; 
    arrIndex++; 

    /* get next value */
    scanf("%d", &val);
   }
    int j = 0;
    for(j = 0; j < size ; j++)
    {
        printf("%d \t", arr[j]);
    }
}

【问题讨论】:

    标签: arrays c dynamic


    【解决方案1】:

    数组的大小保持为 1,并且在增加 size 变量时不会增加。

    您的代码一直工作到第 8 个元素,因为数组之后到第 7 个元素的相邻内存必须是空闲的。 在 C 数组中,索引越界未检查,这是程序员的责任。

    如果你想增加或减少数组的大小,你可以在while循环中使用realloc

    arr=(int*)realloc(arr,sizeof(int)*size);
    

    还要更正代码中的 if 条件,最初 arrayindex 为 0,size 为 1,结果为 false。

    如果(arrIndex >= 大小)

      {
        size++;
    
      }
    

    【讨论】:

      猜你喜欢
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2015-10-09
      • 1970-01-01
      相关资源
      最近更新 更多