Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use pointer arithmetic on pointers to void pointers?

Tags:

c

pointers

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?

like image 510
halfquarter Avatar asked Sep 06 '18 02:09

halfquarter


People also ask

Can we perform pointer arithmetic on void pointer in C?

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.

Can you cast any pointer to a void pointer?

Any pointer to an object, optionally type-qualified, can be converted to void* , keeping the same const or volatile qualifications.

What is pointer arithmetic void pointer?

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.

Which is not allowed in pointer arithmetic?

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.


2 Answers

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.

like image 167
P.W Avatar answered Oct 09 '22 03:10

P.W


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
like image 35
user253751 Avatar answered Oct 09 '22 03:10

user253751