在 c 中创建动态数组在 realloc() 时出错

Creating dynamic array in c gives error at realloc()

我正在尝试用 C 编写一个动态数组,我几乎做到了 it.Now 我卡在了一个点,在使用 realloc() 插入该错误时出现错误。这是我的代码:

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

   typedef struct {

     int *array;//pointer that points to the start of the contiguous  allocated blocks(an array of int)

     size_t used;//array used

     size_t size;//array total size
   }D_Array;


   void alloc_array(D_Array *a, int initial_size)
  {
    //allocate contiguous memory blocks and point a pointer to its beginning address...
    a->array = (int*)malloc(initial_size*sizeof(int));
    a->used = 0;
    a->size = initial_size;
  }


  void insert_array(D_Array *a, int element)
  {
   if(a->used == a->size)
   {
    //allocate one more space and then insert in array
    a->array = (int*)relloc(a->array,(a->size)*sizeof(int)); 
   }
    a->array[a->used++] = element;
  }


  void free_array(D_Array *a)
  {
   free(a->array);
   a->array = NULL;
   a->used = a->size = 0;
  }

  int main()
  {

   D_Array a; 
   int i=0, initial_size=0, insert_element=0;

   printf("Enter the initial size of array :");
   scanf("%d",&initial_size);
   alloc_array(&a, initial_size);

   printf("\nEnter the elements to be inserted initially");
   for(i=0 ; i<initial_size ; ++i)
   {
    scanf("%d",&insert_element);
    insert_array(&a, insert_element);
   }
    a.array[0] = 3;
   for(i=0 ; i<initial_size ; ++i)
   {
    printf("%d",*((a.array)+i));
   }
  }

问题出在方法 "insert_array" 上,但我不知道 why.Everything 我觉得没问题。

[来自 的更新:]

编译器给出:

quicksort.c:32:14: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] a->array = (int*)relloc(a->array,(a->size)*sizeof(int)); ^ /tmp/ccXTwlHh.o: In function insert_array': quicksort.c:(.text+0x8d): undefined reference to relloc' collect2: error: ld returned 1 exit status

您的 realloc 调用有两个问题:第一个是如果 realloc 失败和 returns NULL 会发生什么。这就是为什么你不应该重新分配你传递给 realloc 调用的变量。

第二个问题,也可能是您遇到问题的原因,是您实际上并没有调整数组的大小,而是使用与之前完全相同的大小重新分配它,意思是当你下次做

a->array[a->used++] = element;

您的索引越界,将会有 未定义的行为

除了已经说过的内容之外,您还写了 relloc 而不是 realloc。所以可能有一个打字错误阻碍了编译。