http://stackoverflow.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?
|
7 Answers
165 +100 | Final conclusion: arithmetic on a GCC allows it as an extension, see (note that this section is part of the "C Extensions" chapter of the manual). Clang and ICC likely allow 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. | ||||||||||||||||||||
|
48 | Pointer arithmetic is not allowed on | ||||||||
|
12 | You can't do pointer arithmetic on | ||
|
12 | cast it to a char pointer an increment your pointer forward x bytes ahead. | ||||
|
6 | You have to cast it to another type of pointer before doing pointer arithmetic. | ||
|
3 | 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. void *p = malloc(sizeof(char)*10);p++; //compiler does how many where to pint the pointer after this increment operationchar * c = (char *)p;c++; // compiler will increment the c by 1, since size of char is 1 byte. | |||
|
-1 | 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) | ||||||||
|
void
pointer which points to data of sizex
is incremented, how does it get to pointx
bytes ahead?" It doesn't. Why can't people who have such questions test them before asking - y'know, at least to the bare minimum where they check whether it actually compiles, which this doesn't. -1, can't believe this got +100 and -0. – Aug 20 at 6:30