You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++指针输出一致性疑问:学习指针时的代码运行问题求助

Understanding the Unexpected Output in Your C++ Pointer Code

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 = 10 and a pointer p pointing to its address.
  • You declare a char c2 = 'c' (which stores the ASCII value 99 in 1 byte of memory) and a pointer p2 pointing to it.
  • You cast p2 to a void* (this is correct for printing the address, since cout treats char* 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:

  1. Mismatched Type Size & Memory Access
    A char typically takes up 1 byte of memory, while an int usually takes 4 bytes (this depends on your platform, but it's the most common case). When you cast p3 (which points to a 1-byte char) to an int* and dereference it, you're telling the compiler to read 4 consecutive bytes starting from c2's address. But only the first byte holds valid data (99 for 'c'); the other 3 bytes are uninitialized stack memory (could be leftover values from other variables, random garbage, or even invalid memory).

  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:58:57