When a pointer to a particular type (say int
, char
, float
, ..) is incremented, its value is increased by the size of that data type. If a void
pointer which points to data of size x
is incremented, how does it get to point x
bytes ahead? How does the compiler know to add x
to value of the pointer?
Pointer arithmetic for void pointer in C
cpointer-arithmeticvoid-pointers
Best Answer
Final conclusion: arithmetic on a
void*
is illegal in both C and C++.GCC allows it as an extension, see Arithmetic on
void
- and Function-Pointers (note that this section is part of the "C Extensions" chapter of the manual). Clang and ICC likely allowvoid*
arithmetic for the purposes of compatibility with GCC. Other compilers (such as MSVC) disallow arithmetic onvoid*
, and GCC disallows it if the-pedantic-errors
flag is specified, or if the-Werror-pointer-arith
flag is specified (this flag is useful if your code base must also compile with MSVC).The C Standard Speaks
Quotes are taken from the n1256 draft.
The standard's description of the addition operation states:
So, the question here is whether
void*
is a pointer to an "object type", or equivalently, whethervoid
is an "object type". The definition for "object type" is:And the standard defines
void
as:Since
void
is an incomplete type, it is not an object type. Therefore it is not a valid operand to an addition operation.Therefore you cannot perform pointer arithmetic on a
void
pointer.Notes
Originally, it was thought that
void*
arithmetic was permitted, because of these sections of the C standard:However,
So this means that
printf("%s", x)
has the same meaning whetherx
has typechar*
orvoid*
, but it does not mean that you can do arithmetic on avoid*
.