http://*.com/questions/3523145/pointer-arithmetic-for-void-pointer-in-c
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?
|
Final conclusion: arithmetic on a GCC allows it as an extension, see Arithmetic on The C Standard SpeaksQuotes are taken from the n1256 draft. The standard's description of the addition operation states:
So, the question here is whether
And the standard defines
Since Therefore you cannot perform pointer arithmetic on a NotesOriginally, it was thought that
However,
So this means that Editor's note: This answer has been edited to reflect the final conclusion. |
|||||||||||||||||||||
|
Pointer arithmetic is not allowed on |
|||||||||
|
You can't do pointer arithmetic on |
|||
cast it to a char pointer an increment your pointer forward x bytes ahead. |
|||||
|
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.
|
||||
Compiler knows by type cast. Given a
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) |
|||||||||
|