void pointer increment

girish4c's Avatar, Join Date: May 2010
Newbie Member
hi all,,
if i increase void pointer, in gcc compiler am not getting any error but same its error in VC compiler..


so please let me know wat i need consider as per standards in C?

int i;

void *ptr;
ptr=&i;

ptr++; //ERROR IN VC BUT NO ERROR IN GCC
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
If you increment a pointer to a thing, the pointer is not just increased by 1 byte but by the size of that thing. So a pointer to char will increment by 1 char, a pointer to int will increase by sizeof(int) (typically 4 bytes), a pointer to a struct S will increase by sizeof (struct S), so that the pointer points to the "next" object, which is more use than it pointing to the next byte in memory.

Code:
int i[10], *pi;
char j[10], *pj;
void *k;
k=&i[0];
pi=&i[0];
pi++; k++; // should both increase by the same?
k=&j[0];
pj=&j[0];
pj++; k++; // should both increase by the same?
But void* does not point to anything with a fixed size, and sizeof(void) is meaningless, so the compiler cannot tell in general what it points at, so it cannot determine by how much it should increment. So I think the most appropriate behaviour is to throw an error. But maybe this is left undefined by the Standard, in which case both behaviours would be correct.

In the code above you can tell from the context what k points to. But if we passed k into a function then the compiler has no way at all to determine what sizeof(*k) is.

Googling around (which you should try some time rather than assuming you're the first person ever in the history of computer programming to have thought of this), it seems the VC++ behaviour corresponds to ANSI standard behaviour so maybe VC++ is ANSI standard by default and gcc is not. Try enabling ANSI standard compliance for gcc, there's probably a flag (and before you ask, try googling it and/or RTFM), and this should result in an error from gcc.