我一直在尝试 O(n ^2) 排序算法只是为了练习 C,但遇到了这个恼人的“realloc():无效指针”错误,并且无法找出原因。我看过其他解释,但它们没有太大帮助。
#include <stdio.h>
#include <stdlib.h>
int* removeIndex(int* list, int index, int len){
for(int i = index; i < len - 1; i++){
list[i] = list[i+1];
}
return realloc(list, len - 1);
}
int* sort(int* unsorted, int len){
int* sorted = malloc(len * sizeof(int));
for(int placement = 0; placement < len; placement++){
int smallest_index = 0;
int smallest = unsorted[smallest_index];
int len_unsorted = len - placement;
for(int i = 0; i < len_unsorted; i++){
if (unsorted[i] < smallest){
smallest = unsorted[i];
smallest_index = i;
}
}
unsorted = removeIndex(unsorted, smallest_index, len_unsorted);
sorted[placement] = smallest;
}
return sorted;
}
int main()
{
int len = 5;
int unsorted[5] = {5,4,3,2,1};
int* sorted = sort(unsorted, len);
for(int i = 0; i < len; i++){
printf("%d\n", sorted[i]);
}
return 0;
}
顺便说一句,为什么我写的时候会出现错误
int len = 5;
int unsorted[len] = {5,4,3,2,1};
所以我必须强制将其写为 int unsorted[5] = {5,4,3,2,1};
干杯
最佳答案
传递给realloc
的指针指向一个具有自动存储持续时间的数组,该数组在main()
中声明和初始化,而不是指向先前分配的内存块使用 malloc
、calloc
或 realloc
。
来自realloc [强调]
Reallocates the given area of memory. It must be previously allocated by malloc(), calloc() or realloc() and not yet freed with a call to free or realloc. Otherwise, the results are undefined.
关于C-realloc() : invalid pointer error encoutered,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51456093/