I have written a program for heap sort and I tried to have both the array and the size of the array in a single structure but there seems to be some error in my code (I think it's in the initializing part). Here is my code.
#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);
}
I compiled it in linux platform and the error I got was Segmentation fault (core dumped) Can someone explain why I got this error and give a possible solution to this.
h->nandh->arrdirectly after declaringhas an uninitialisedheap *cannot be correct. Instead, declarehas aheapand useh.nandh.arr. Remember thath->nis nothing more than a synonym for(*h).n, and using the*operator on an uninitialised pointer will result in a segmentation fault at best.