Void* arithmetic

Hello everyone,

For a school project I am working on, I must use an array of unspecified objects:


void* voidarray;


In addition to this pointer, I need another one that points to a specific location beyond that address:


void* voidarray2 = voidarray + offset; // offset is an integer


However, I just learned that void* arithmetic is not allowed in C. How can I get voidarray2 to point to the specific location without using void* arithmetic?



NewProgrammer
Last edited on
You almost certainly shouldn't be using void* for this. void* is a pointer to anything. You clearly need a pointer to a some kind of object.

You should define an object hierarchy and use a pointer to that.

You'd only need a pointer to one past the end if you intend to iterate over a list of these objects, so there's a lot more going on than you're saying. You reall need to be clear in your mind what you want to do in order to instruct the computer.
However, I just learned that void* arithmetic is not allowed in C.

You shouldn't do it, but it is supported... and a void pointer behaves a lot like a char pointer.

How can I get voidarray2 to point to the specific location without using void* arithmetic?

Do the pointer arithmetic on non-void pointers (cast them), and use the void pointer to store the result, I guess?
Last edited on
My project is to give my own implementation of malloc and free (called "my_malloc()" and "my_free") based on the buddy system.

I am using void pointers because I cannot predict what object a user of my program will want to allocate. Hence, "my_malloc()" returns a void* array, which the user can cast into what they want.



Here is where I run into a challenge: For those familiar with the buddy system, we know that if a user requests an 8k block, and the smallest block available is a 32k block, we must split the 32k block in half twice.

The split() function is the challenge. Before splitting anything, there is already a pointer that points to the head of the 32k block. Since I am splitting it, I want a pointer to point midway through the block so that it will point to the head of the right buddy. Doing that without doing void* arithmetic is my challenge at the moment.
Last edited on
You allocator seems to be working with blocks of chars (or unsigned chars). So use that internally. But you cast the pointer you return to a void*. You certainly don't use void* internally because you're working with blocks of bytes.
Char pointers are a great idea, since each char is a single byte. Thank you, kbw.

NewProgrammer
Topic archived. No new replies allowed.