gpt4 book ai didi

无法通过 malloc

转载 作者:行者123 更新时间:2023-11-30 20:06:29 25 4
gpt4 key购买 nike

你好,我正在尝试在 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;

在这个方法中,我创建并插入堆中的所有 double 。但我无法通过数组 malloc。我尝试了一切,但仍然无法使其工作!任何帮助是极大的赞赏,谢谢你们。

最佳答案

问题出在其他地方。 (尽管前面提到的malloc也是一个问题。)

您没有在 main 例程中正确初始化初始结构 array:

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]);
}

这会将数据写入 array1[1]array1[n],但最后一个值在 C 中无效。长度为 n的数组0 开始,到 n-1 结束。将循环更改为

for (i=0;i<n;i++)

最有可能发生的情况是随机内存被覆盖,因此您会在“其他地方”收到不相关的错误。

关于无法通过 malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23597924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com