我一直认为,指针递增/递减是这样的操作:
new_ptr=old_ptr+sizeof(type)*count
所以使用 int * 它将是:
old_ptr=0 //int *ptr=0
count=1 //int count=1
new_ptr=old_ptr+sizeof(int)*count = 0+4*1 = 0x0004 //ptr+=count;
并且 void = 0 的大小,因此使用 += 增加 void_ptr 不应该改变它。但我可能弄错了。另一件事是 ++ 运算符,它会引发错误。那么如果 ++ 抛出错误,为什么 += 也不抛出呢?示例代码:
#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;
}
输出:
Before:
int_ptr: 0
void_ptr: 0
After ++:
int_ptr: 0x4
void_ptr: 0
After +=:
int_ptr: 0x8
void_ptr: 0x1
有人可以解释一下吗?