cplusplus.comのチュートリアルの「void ポインター」の例で、次のように比較してみます。なぜまだ*
括弧が必要なのですか?いいえの場合はどうなり*
ますか?
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' になります)。