954,506 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Find void array index from pointer

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?

mmonaco27
Light Poster
43 posts since Sep 2006
Reputation Points: 10
Solved Threads: 0
 

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.

twomers
Posting Virtuoso
1,877 posts since May 2007
Reputation Points: 453
Solved Threads: 57
 

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)

mmonaco27
Light Poster
43 posts since Sep 2006
Reputation Points: 10
Solved Threads: 0
 

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.

twomers
Posting Virtuoso
1,877 posts since May 2007
Reputation Points: 453
Solved Threads: 57
 

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;
}
mmonaco27
Light Poster
43 posts since Sep 2006
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You