在cplusplus.com教程中的「void pointers」示例中,我嘗試比較如下。爲什麼我們仍然需要*
括號?發生什麼事時沒有*
?接受的解決方案後增加指針時有或沒有星號
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灰色的答案。 pchar
的地址遞增,指向無意義的位置。但是因爲main
中的變量a
是cout
而不是pchar
,所以此cout
仍然會打印一個有點合理的值(在本例中爲'x')。