【问题标题】:Cant get passed a malloc [closed]无法通过 malloc [关闭]
【发布时间】: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


【解决方案1】:

问题出在其他地方。 (虽然前面提到的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++)

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

【讨论】:

  • 哇,它真的很有效,非常感谢!多么愚蠢的错误啊!我在这个程序上工作了 3 个小时,仍然没有找到任何东西!!谢谢!!
  • @user3626500:那么欢迎来到 SO!请确保阅读About 页面一段时间——但你做得很好,这是第一次发布海报!您可能想阅读What should I do when someone answers my question
【解决方案2】:

这一行是错误的。

struct heap *h=(struct heap*)malloc(sizeof(struct heap*));

必须是:

struct heap *h=malloc(sizeof(struct heap));

【讨论】:

  • 再次无法通过 struct heap *h=malloc(sizeof(struct heap));线。这是粉碎!
  • 如果崩溃,您必须描述崩溃。是段错误吗?它指的是哪条线? 究竟是什么错误信息?
【解决方案3】:

这些行放在一起没有意义:

array1=(double*)malloc(sizeof(double)*n);

for(i=1;i<=n;i++ ){

你分配了一个包含 n 个元素的数组,然后尝试一直写到数组的末尾,并且在末尾之后有 1 个元素!

相反,您的 for 循环应如下所示:

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

记住
在 C 中,数组是从零开始的,而不是从 1 开始的。
第一个元素是array1[0]。最后一个元素是array1[n-1]
并且元素 array1[n]INVALID

【讨论】:

    猜你喜欢
    • 2022-07-06
    • 1970-01-01
    • 2014-09-20
    • 2018-04-22
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 2019-12-15
    • 2015-02-13
    相关资源
    最近更新 更多