0

I'm working on a project where I'm implementing a binary heap in C. I'm given Python code for this task, and I essentially need to "translate" the Python to C. I'm having some trouble dealing with translating "self" in Python to the equivalent in C.

Here's the Python code for initializing a binary heap in Python:

def __init__(self, items=None):
    self.heap = [None]
    if items is None:
        self.heap_size = 0
    else:
        self.heap += items
        self.heap_size = len(items)
        self._build_heap()  # this a call to another method

I'm pretty sure I need to define a struct BinaryHeap and fill in this information. How would I say something like "self.heap = [None]" or "self.heap_size = 0" in C? Note: I'm fairly new to C, haha.

TyCharm
  • 325
  • 1
  • 2
  • 16

1 Answers1

1

You would declare a struct BinaryHeap as you say, then you would do something like this:

/* This is the init function */
BinaryHeap *BinaryHeap_init(void **items):
{
    BinaryHeap *self = malloc(sizeof(BinaryHeap));
    if (self) {
        self->heap = NULL; /* This is how you set a property */
        if (items == NULL) {
            self->heap_size = 0;
        }
        /* This is how you call a "method" */
        BinaryHeap_build_heap(self);
    }
    return self;
}

/* This is how you define a "method" */
void BinaryHeap_build_heap(BinaryHeap *self)
{
    /* Do something with self->heap, etc. */
} 

/* You also need a destructor */
void BinaryHeap_delete(BinaryHeap *self)
{
    if (self) {
        /* Destroy self->heap here */
        free(self);
    }
}

That's the basics of "objects in C", but I think you may have bitten of more than you can chew if you're not very familiar with C. There are no built-in data structures like lists in C, so you would need to implement your own or find open-source ones.