Possible Duplicate:
void * arithmetic
Hi guys I have a small question regarding pointer increment in C. First let say that I know that ptr++, where ptris a pointer will increment as much as the sizeof(*ptr). Also I know that when doing *ptr, the compiler knows it has to grab sizeof(*ptr) bytes from memory.
The second part helps me understand why the following does not even compile:
int main(){
int a = 3;
void* b = &a;
printf("%d\n", *b);
return 0;
}
Because the compiler does not know the size of a variable of type void. However, I’m a little bit confused about the following code:
int main(){
int a = 3;
void* b = &a;
printf("%p\n", b);
b++;
printf("%p\n", b);
}
So, my two questions are:
-
How is the compiler able to know how much it should increment
b? -
Why does it increment only one byte (at least in my machine is one byte)?
1) it doesn’t, 2) that’s undefined behaviour.
voidis an incomplete type, so it doesn’t have a well-defined size, so you cannot do pointer arithmetic with its pointers.Typically you will want
charpointers for byte-wise memory fiddling.If you compile with all compiler warnings enabled, you will spot such problematic code.