I have a header class containing the following struct definitions:
struct Entry {
int key;
char *value;
};
typedef struct Entry Entry;
struct Heap {
int capacity;
int size;
Entry **elements;
};
typedef struct Heap Heap;
And, I'm trying to write a function makeHeap that "returns a pointer to some newly allocated Heap with the given capacity, a size of 0, and an elements array allocated with the given capacity."
The elements array is what I'm not entirely sure about. It's supposed to contain pointers (references) to Entry objects. Which I am not sure if I'm doing correctly here. In order to make an array that holds references to Entry objects, I declare a double pointer array (due to the Entry having a pointer in it) and then I initialize elements iteratively, and then set my newly created heap's elements pointer to a pointer of the **elements array I just built.
I'm not getting any compile errors, but I honestly don't know if I am doing this correctly. Any input would be greatly appreciated. I did some searches but couldn't find the case where a struct was defined quite in the way mine is with the double pointer array Entry** elements.
Also, as far the syntax between Entry** elements and Entry **elements are these interchangeable? As in they are both declaring an array that holds double pointers of type Entry?
Heap *makeHeap(int capacity) {
//Make the heap
Heap* theHeap = calloc(1, sizeof(Heap));
//set its capacity to param
theHeap->capacity = capacity;
//inital size is 0
theHeap->size = 0;
//elements contains pointers (references) to Entry objects.
Entry **elements[capacity];
//iterate capacity times allocating an entry reference for each element to be placed
int i = 0;
for (; i < capacity; i++) {
elements[i] = calloc(1, sizeof(Entry));
}
theHeap->elements = *elements;
return theHeap;
}
elementsarray is actually allocated on the stack when you call themakeHeapfunction. This is actually incorrect, since when the function returns, the array will be removed from the stack, so then your heap instance will point to location on the stack that no longer exists. You can solve this by also creating your elements array on the heap.