我已经写了一个堆排序的程序,我试图将数组和数组的大小都放在一个结构中,但我的代码中似乎有一些错误(我认为是在初始化部分)。这是我的代码。
#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.
发布于 2020-10-12 22:52:03
通过这样做heap *h;,您声明了一个指向堆结构的指针,但是这个指针在这一点上实际指向了什么呢?
你只需要为你的堆分配内存:
void main()
{
heap *h;
// Alloc and initialize the pointer to the heap
h = malloc(sizeof(heap));
scanf("%d",&h->n);
h->arr = 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);
// Don't forget to free the heap as well!
free(h);
}此外,最好不要强制转换malloc的返回值。
发布于 2020-10-12 22:58:33
用一种不同的方式:
typedef struct heap
{
size_t n;
int arr[];
}heap;只需要一个malloc和free。
size_t size;
heap *h;
if(scanf("%zu", &size) != 1) { /* error handling*/};
h = malloc(sizeof(*h) + size * sizeof(h -> arr[0]));
if(!h) { /* error handling*/};
h -> size = size;
/*...... */
free(h);发布于 2020-10-12 23:05:21
当你声明heap *h;时,你声明了一个指针,但是在声明之后,你永远不会将h初始化为指向任何地方。
你可能想要这个:
int main()
{
heap h; // now h is a heap and no more a pointer to heap
scanf("%d", &h.n);
h.arr = malloc(h.n * sizeof(int)); // the cast to (int*) is useless
for (int i = 0; i < h.n; i++)
scanf("%d", h.arr + i); //BTW: &h.arr[i] would be more readable
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);
}在build_heap和build_heap中可能会有更多的问题,但我不能告诉你更多,因为你没有展示这些函数。
https://stackoverflow.com/questions/64319984
复制相似问题