I'm implementing a heapsort on a void array. But I'm having trouble with line 6:

void siftdown(char *start, char *end, size_t size)
{
	char *curr = start;
	char *child;
	
	while (curr*2 + size <= end)

I cast the pointers to char because they have a length of one, and I multiply the index i want by the size of the data to shift to the right position. For example:

char *pos = (char *)arr + 5*size

will shift me to index 5.
I want to reference twice the current position in the array + 1. I know I can't multiply the pointer by 2, but how might I do this?

Is there any way you can keep track of the current position? If there is you can multiply that by two because, as you stated, you know you can't multiply the pointer by two. However, one can do multiplication via addition.

I have a version where instead of manipulating the pointers, I keep track of the indices. Then when I want to reference one I simply add the index * size to the base of the array.

So yes, I can keep track of the index but I'm trying to convert it to using pointers (to speed it up)

Not too sure how much faster you'll make it...
If you have a pointer to the start of your variable, subtract the current from it and add the difference, perhaps.

This seems to work here, but when I actually apply it to my algorithm, it fails to sort.

#include <stdio.h>
#include <stdlib.h>

int main()
{
	void *array = calloc(10, sizeof(int));

	for (int i = 9; i >= 0; i--)
	{
		((int *)array)[9-i] = i;
	}

	for (int i = 0; i < 10; i++)
	{
		printf("Ind %i == %i\n", i, *((int *)array+i));
	}

	char *cur = (char *)array + 2*sizeof(int);
	printf("\n\nInd 2 == %i\n\n", *(int *)cur);


	char *test = cur + (cur - (char *)array);
	printf("\n\nInd 5 == %i\n\n", *(int *)test);

	return 0;
}
This article has been dead for over six months. Start a new discussion instead.