I know you can't utilize pointer arithmetic on void pointers, but could you theoretically do pointer arithmetic on pointers to void pointers, since sizeof(void *)
would yield an answer of how many bytes a pointer takes on your system?
Pointer arithmetic cannot be performed on void pointers because the void type has no size, and thus the pointed address cannot be added to. However, there are non-standard compiler extensions allowing byte arithmetic on void* pointers. Pointers and integer variables are not interchangeable.
Any pointer to an object, optionally type-qualified, can be converted to void* , keeping the same const or volatile qualifications.
The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means that it points to the address of variables. It is also called the general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.
We can't perform every type of arithmetic operations with pointers. Pointer arithmetic is slightly different from arithmetic we normally use in our daily life. The only valid arithmetic operations applicable on pointers are: Addition of integer to a pointer.
Pointer arithmetic is not permitted on void*
because void
is an incomplete object type.
From C Committee draft N1570:
6.5.6 Additive operators
...
2. For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type.
But it is permitted on void**
because void*
is NOT an incomplete object type. It is like a pointer to a character type.
6.2.5 Types
...
19. The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.
...
28. A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.
Yes, pointer arithmetic works on pointers to void pointers (void**
). Only void*
is special, void**
isn't.
Example:
void *arrayOfVoidPtr[10];
void **second = &arrayOfVoidPtr[1];
void **fifth = second + 3; // pointer arithmetic
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With