官方释义如下:
/* Re-allocate the previously allocated block
in PTR, making the new block SIZE bytes long. */
/* __attribute_malloc__ is not used, because if realloc returns
the same pointer that was passed to it, aliasing needs to be allowed
between objects pointed by the old and new pointers. */
extern void *realloc (void *__ptr, size_t __size)
__THROW __attribute_warn_unused_result__;
将之前创建的块区重新分配为 __size 的 大小,并返回新的地址指针。
在insert函数中,因为是插入新的元素,链表扩张,元素加一,原先 list->arr 长度不符合,需要扩张空间,所以使用了 realloc函数。
list->arr = (int*)realloc(list->arr, sizeof(int)*list->length + 1);
从上下函数分析。 list->arr 是一个 int 型数组。因为要插入一个新的int型元素,所以要对原先数组扩张,但还要维护 list->arr 的首地址,只能采用 realloc 函数。
但是你的这个函数不报错吗?增加一个int值,不管是维护指针还是内存,都需要4个字节的空间。
应该是
list->arr = (int*)realloc(list->arr, sizeof(int)*(list->length + 1));
... 展开详请