在cplusplus.com教程中的“空指针”示例中,我尝试进行如下比较。为什么我们还需要*
括号?没有时会发生什么*
?
void increase(void* data, int psize) {
if (psize == sizeof(char)) {
char* pchar;
pchar = (char*) data;
cout << "pchar=" << pchar << endl;
cout << "*pchar=" << *pchar << endl;
//++(*pchar); // increases the value pointed to, as expected
++(pchar); // the value pointed to doesn't change
} else if (psize == sizeof(int)) {
int* pint;
pint = (int*) data;
//++(*pint); // increases the value pointed to, as expected
++(pint); // the value pointed to doesn't change
}
}
int main() {
char a = 'x';
int b = 1602;
increase(&a, sizeof(a));
increase(&b, sizeof(b));
cout << a << ", " << b << endl;
return 0;
}
接受解决方案后更新)根据@Cody Gray的回答,我试图弄清楚我没有得到什么。的地址pchar
递增以指向无意义的位置。但是因为变量a
inmain
是cout
ted 而不是pchar
,这cout
仍然会打印出一个有意义的值(在本例中为“x”)。