【发布时间】:2012-05-14 23:28:08
【问题描述】:
在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 的地址递增以指向无意义的位置。但是因为main 中的变量a 是coutted 而不是pchar,所以这个cout 仍然会打印出一个有意义的值(在这个例子中它是'x')。
【问题讨论】:
标签: c++ pointers void-pointers