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?
相关问题
- Multiple sockets for clients to connect to
- Do the Java Integer and Double objects have unnece
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
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*
.Editor's note: This answer has been edited to reflect the final conclusion.
You have to cast it to another type of pointer before doing pointer arithmetic.
Void pointers can point to any memory chunk. Hence the compiler does not know how many bytes to increment/decrement when we attempt pointer arithmetic on a void pointer. Therefore void pointers must be first typecast to a known type before they can be involved in any pointer arithmetic.
cast it to a char pointer an increment your pointer forward x bytes ahead.
You can't do pointer arithmetic on
void *
types, for exactly this reason!Compiler knows by type cast. Given a
void *x
:x+1
adds one byte tox
, pointer goes to bytex+1
(int*)x+1
addssizeof(int)
bytes, pointer goes to bytex + sizeof(int)
(float*)x+1
addressizeof(float)
bytes, etc.Althought the first item is not portable and is against the Galateo of C/C++, it is nevertheless C-language-correct, meaning it will compile to something on most compilers possibly necessitating an appropriate flag (like -Wpointer-arith)