我试图用C编写一个动态数组,我几乎做到了it.Now,我的代码是使用realloc().Here插入错误时,它会产生错误:
#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对我来说似乎很好。
[comment更新:]
编译器给出:
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
发布于 2016-05-21 22:33:02
另外,您已经编写了relloc
,而不是realloc
。因此,可能有一个错误阻碍了汇编。
发布于 2016-05-21 22:29:22
realloc
调用有两个问题:第一个问题是,如果realloc
失败并返回NULL
,会发生什么。这就是为什么不应该将变量重新分配到传递给realloc
调用的变量。
第二个问题,也可能是导致您的问题的原因是,您没有实际调整数组的大小,而是使用与前面完全相同的大小重新分配数组,这意味着您下一步要做的是
a->array[a->used++] = element;
您正在进行超出界限的索引,并且将具有未定义的行为。
https://stackoverflow.com/questions/37371248
复制