I'm trying to implement a generic function pointer which does basic arithmetic (basic linked-list traversal) using a type based on the argument that the function received.
So to reverse position in a linked list:
Code:
void *reverse(void *init, unsigned int N)
{
void *ptr = init;
unsigned int i;
for(i = 0; i < N; i++)
ptr = ptr->prev;
return ptr;
}
As the first argument this function takes an argument init which will be a specific list element of a certain type -- this is established when reverse is called. The function then goes back N elements from init and is supposed to return the resulting pointer (which ought to be of the type of init that was originally passed).
I am missing something here. The compiler wants me to cast ptr. I am curious why this is not working.
Should I do (?):
Code:
void *reverse(void *init, unsigned int N)
{
void *ptr = init;
*((char *)ptr) = *(char *)ptr - N * sizeof(*(char *)ptr);
return ptr;
}