If I do this:
int x = 10;
void *ptr = &x;
ptr++;
The line "ptr++" gives an error.
However, If instead of "ptr++" I do this:
ptr = ptr + 1;
It works just fine. What could be the reason?
If I do this:
int x = 10;
void *ptr = &x;
ptr++;
The line "ptr++" gives an error.
However, If instead of "ptr++" I do this:
ptr = ptr + 1;
It works just fine. What could be the reason?
Void pointer arithmetic is illegal in standard C but usually allowed by gcc extensions.
Conceptually, this is because when you perform an increment on a pointer, it will actually perform scaling in the background to add the proper number of bytes (given by the pointer's type) to get you to the next unit of data.
Since a void pointer could point to any type, it's saving you from accessing parts of memory differently than intended. The compiler can't possibly determine how to scale the addition since it has no knowledge of the type pointed to.
In standard C, ptr = ptr + 1
is also illegal for the same reason. The reason you're seeing one work is due to the same issues with gcc extensions.
Both will give you errors in gcc
when using the -pedantic-errors
flag.
C standard forbids pointer arithmetics on void*. Depends on compiler though. The reason is simple, C is not assembly :-)