C++指针输出一致性疑问:学习指针时的代码运行问题求助
Hey there! Let's dig into why that last line of your code is giving you confusing results—this is a common pitfall when working with pointer type casts in C++.
First, let's recap what your code is doing step by step:
- You declare an
int x = 10and a pointerppointing to its address. - You declare a
char c2 = 'c'(which stores the ASCII value99in 1 byte of memory) and a pointerp2pointing to it. - You cast
p2to avoid*(this is correct for printing the address, sincecouttreatschar*as a string pointer instead of an address). - The problematic line is this one:
cout<<"Content of address in p2/p3:"<< *(static_cast<int *>(p3))<<endl;
Why This Line Causes Unexpected Output
There are two core issues here:
Mismatched Type Size & Memory Access
Achartypically takes up 1 byte of memory, while anintusually takes 4 bytes (this depends on your platform, but it's the most common case). When you castp3(which points to a 1-bytechar) to anint*and dereference it, you're telling the compiler to read 4 consecutive bytes starting fromc2's address. But only the first byte holds valid data (99for 'c'); the other 3 bytes are uninitialized stack memory (could be leftover values from other variables, random garbage, or even invalid memory).Undefined Behavior
The C++ standard defines this kind of cross-type pointer cast and dereference as undefined behavior. That means there's no guarantee what your program will do—you might get a random number, a value that changes between runs, or even a crash in some cases. The compiler doesn't have to handle this scenario predictably.
The Fix
If you want to correctly read the value stored in c2, you need to cast p3 back to the original type (char*) instead of int*:
cout<<"Content of address in p2/p3:"<< *(static_cast<char *>(p3))<<endl;
This will only read the 1 byte that actually holds c2's value, so you'll see c printed (or 99 if you cast the result to int like static_cast<int>(*(static_cast<char *>(p3)))).
A Quick Note on void*
Your use of static_cast<void*>(p2) to print the address is totally correct—since cout will try to print a char* as a null-terminated string, casting to void* forces it to display the raw memory address instead.
内容的提问来源于stack exchange,提问作者N00bie

