如何解决在 bin 排序算法中获取 malloc 断言错误
这是一个 bin 排序程序。我在网上找到了其他方法,但我的老师认为我们是这样的。我是编程初学者,请帮我写代码。
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct Node{
int data;
struct Node *next;
};
//Print array function
void printArray(int arr[],int n){
for(int i=0; i<n; i++)
printf("%d ",arr[i]);
printf("\n");
}
//findMax function for count and bin/bucket sort
int findMax(int arr[],int n){
int max = INT_MIN;
for(int i=0; i<n; i++){
if(arr[i]>max) max=arr[i];
}
return max;
}
//insert function for bins sort
void Insert(struct Node *Bins[],int index){
struct Node *t;
t=(struct Node*)malloc(sizeof(struct Node));
t->data = index;
t->next=NULL;
if(Bins[index] != NULL){
while(Bins[index] == NULL)
Bins[index]= Bins[index]->next;
Bins[index]->next = t;
}
else
Bins[index] = t;
}
//delete function for bin/bucket sort
int Delete(struct Node *Bins[],int i){
int x;
if(Bins[i]->next !=NULL){
struct Node *temp;
temp=(struct Node*)malloc(sizeof(struct Node));
temp=Bins[i]->next;
x=Bins[i]->data;
free(Bins[i]);
Bins[i] = temp;
}
else{
x = Bins[i]->data;
free(Bins[i]);
}
return x;
}
// bin/bucket sort
void BinSort(int arr[],int n){
int max,i,j;
struct Node **Bins;
Bins =(struct Node**)malloc(sizeof(struct Node*));
max = findMax(arr,n);
for(i =0; i<max+1; i++)
Bins[i] = NULL;
for(i=0; i<n; i++)
Insert(Bins,arr[i]);
i=j=0;
while(i < max+1){
while(Bins[i] != NULL)
arr[j++] = Delete(Bins,i);
i++;
}
}
int main(){
int n=10;
int arr[] = {8,5,7,3,2,6,4,11,5};
BinSort(arr,n);
printArray(arr,n);
return 0;
}
该程序使用辅助数组来维护元素的数量,但使用链表,我相应地编写了插入和删除函数。
解决方法
线
Bins =(struct Node**)malloc(sizeof(struct Node*));
错了。您正在使用 max+1
元素,但您只分配了一个元素。您必须分配 max+1
元素。
换句话说,该行应该是:
Bins = malloc(sizeof(struct Node*) * (max+1));
或
Bins = malloc(sizeof(*Bins) * (max+1));
另请注意,malloc()
族的转换结果为 considered as a bad practice。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。