【发布时间】:2014-06-29 03:50:20
【问题描述】:
您好,我正在尝试在 c 中创建一个堆!这是我的堆结构。
struct heap{
double* array;
int maxSize;
int currentSize;
};
这是我的主要内容:
int n;
double *array1,hmax;
struct heap *h;
int i;
printf("\n Enter the number of elements: ");
scanf(" %d",&n);
array1=(double*)malloc(sizeof(double)*n);
printf("\n Forming the heap please wait...\n");
for( i=1;i<=n;i++ ){
array1[i]=(double)rand()/1000;
printf("%.2f /",array1[i]);
}
printf("\n Now the array in heap form is: ");
for( i=1;i<=n;i++ ){
printf("\n %.2f",array1[i]);
}
h=createHeap(array1,n);
而createHeap方法是这样的:
struct heap* createHeap( double array1[],int length ){
int i;
struct heap *h=(struct heap*)malloc(sizeof(struct heap*));
if( !h ){
printf("No free memory system exit...\n");
abort();
}
h->maxSize=length;
h->currentSize=0;
h->array=(double*)malloc(sizeof(double)*(h->maxSize+1));
printf("here");
if( !h->array ){
fprintf(stderr, "Not enough memory!\n");
abort();
}
for( i=0; i<length; i++ ){
h->array[i+1]=array1[i];
}
h->currentSize=length;
for( i=h->maxSize/2; i>0; i-- ){
heapify(h,i);
}
return h;
在此方法中,我在堆中创建并插入所有双精度数。我不能通过数组malloc。我尝试了一切,但我仍然无法让它工作! 任何帮助是极大的赞赏, 谢谢你们。
【问题讨论】:
-
您正在分配指针的大小 --
malloc(sizeof(struct heap*))您需要在其中分配sizeof(struct heap)。 -
是的,但这是通过那里的唯一途径。我不能用 malloc(sizeof(struct heap)) 分配它崩溃,我可以找出原因!!
-
这就是
printf("here")的用途吗?在这些行之后添加fflush(stdout),因为它可能会对您有所帮助。或者使用调试器。顺便说一句,您的数组复制循环也是错误的,它用第一个元素的副本填充数组。 (当然,除非这是你的意图。) -
是的 pprintf("here");是否作为“调试”工具存在。我也想用array1的元素填充堆中的数组,所以我认为它是正确的。所以不知道为什么我不能通过他的 malloc?
标签: c pointers malloc heap-memory