I always thought, that pointer incrementation/decrementation is operation like this:
new_ptr=old_ptr+sizeof(type)*count
So with int * it would be:
old_ptr=0 //int *ptr=0
count=1 //int count=1
new_ptr=old_ptr+sizeof(int)*count = 0+4*1 = 0x0004 //ptr+=count;
And size of void = 0, so incrementing void_ptr by using += should not change it. But I was probably mistaken. Other thing is ++ operator, which throws error. So if ++ throws error, why does += not throw it too? Example code:
#include <stdio.h>
void tell(const char *s,int *i,void *v){
printf("%s: \n int_ptr: %#x\n void_ptr: %#x\n",s,i,v);
}
int main(){
int *int_ptr=0;
void *void_ptr=0;
tell("Before",int_ptr,void_ptr);
int_ptr++; //int_ptr=int_ptr+sizeof(int); = 0x 0004
//void_ptr++; //error: ISO C++ forbids incrementing a pointer of type 'void*'
tell("After ++",int_ptr,void_ptr);
int_ptr+=1; //int_ptr=int_ptr+sizeof(int) = 0x0008
void_ptr+=1;//void_ptr=void_ptr+sizeof(void) WHY DOES THIS WORK AND ++ DOES NOT?! = 0x0001 ?! should be 0x0000, because sizeof void = 0
tell("After +=",int_ptr,void_ptr); //RESULT: void_ptr=0x1, so does that mean, that sizeof void is 1 and it is not 0
return 0;
}
Output:
Before:
int_ptr: 0
void_ptr: 0
After ++:
int_ptr: 0x4
void_ptr: 0
After +=:
int_ptr: 0x8
void_ptr: 0x1
Could someone explain me it?