I have two C functions, which basically operate on a stack data structure. This one pushes a value of type OBJ
which is actually just unsigned long
to the top of the stack. The stack is also grown if necessary.
OBJ Quotation_push_(CzState *cz, CzQuotation *self, OBJ object)
{
if ((self->size + 1) > self->cap) {
self->items = (OBJ *)CZ_REALLOC(self->items, sizeof(OBJ) * (self->cap + 1) * 2);
self->cap = (self->cap + 1) * 2;
}
self->items[self->size++] = object;
return (OBJ)self;
}
The next function inserts an OBJ
into an arbitrary position in the self->items
array. Try as I might, it just won't work properly. I use Quotation_push_
here with a dummy value to get the automatic growth behavior. The problem is that I always see the CZ_NIL
dummy value at the end of the array, with the item I'm trying to insert just overwriting what's in the position already. Here's what I've got so far:
OBJ Quotation_insert_(CzState *cz, CzQuotation *self, OBJ object, int pos)
{
printf("have to move %d OBJ from %d to %d\n", self->size - pos, pos, pos + 1);
Quotation_push_(cz, self, CZ_NIL);
memmove(self->items + ((pos + 1) * sizeof(OBJ)), self->items + (pos * sizeof(OBJ)), sizeof(OBJ) * (self->size - pos));
self->items[pos] = object;
return (OBJ)self;
}
I'm not getting any segfaults or errors, it just doesn't work as expected. Any ideas?