【发布时间】:2021-01-26 21:25:26
【问题描述】:
我已经编写了一个堆排序程序,我试图将数组和数组的大小放在一个结构中,但我的代码中似乎有一些错误(我认为它在初始化部分)。 这是我的代码。
#include<stdio.h>
#include<stdlib.h>
int cmp;
typedef struct heap
{
int *arr, n;
}heap;
void main()
{
heap *h;
scanf("%d",&h->n);
h->arr = (int*)malloc(h->n*sizeof(int));
for(int i=0; i<h->n; i++)
scanf("%d",h->arr+i);
build_heap(h);
heap_sort(h);
for(int i=0; i<h->n; i++)
printf("%d ",h->arr[i]);
printf("\n%d\n",cmp);
free(h->arr);
}
我在linux平台编译,得到的错误是Segmentation fault (core dumped) Can someone explain why I got this error and give a possible solution to this.
【问题讨论】:
-
在将
h声明为未初始化的heap *后直接使用h->n和h->arr是不正确的。相反,将h声明为heap并使用h.n和h.arr。请记住,h->n只不过是(*h).n的同义词,在未初始化的指针上使用*运算符最多会导致分段错误。