如何确认指向常量字符的指针已被重新分配至新地址
问题描述
我正在学习C++,遇到以下问题:将指向常量的指针重新赋值给新字符变量后,无法显示预期的地址值。
在提供的代码中,我原本认为执行pointer_to_const = &c;后,指针应显示与指向字符变量b时不同的新地址,但运行代码后却未得到预期结果。
Constant Pointer部分的输出符合预期,但Pointer to Const部分存在两个疑问:
- 执行
pointer_to_const = &c;后,用cout输出pointer_to_const时看不到新地址,难道c没有唯一地址吗? - 在Pointer to Const部分可以用
cout显示&pointer_to_const,但无法直接正确显示&b或&c。
我参考C语言的实现方式,尝试在C++中完成该操作,以此学习相关知识。
代码示例
#include <iostream> int main(){ char a = 'a'; char b = 'b'; char c = 'c'; // Constant Pointer std::cout << "-------Constant Pointer---------" << std::endl; char *const constant_pointer = &a; std::cout << "Constant pointer a has an address of: " << static_cast<void*>(constant_pointer) << " and value of: " << *constant_pointer << std::endl; *constant_pointer = 'x'; std::cout << "Constant pointer a has an address of: " << static_cast<void*>(constant_pointer) << " and a new value of: " << *constant_pointer << std::endl; // Pointer to Const std::cout << std::endl; std::cout << "--------Pointer to Const--------" << std::endl; const char *pointer_to_const = &b; // **Edit** - section updated to properly display address pointed to by pointer_to_const std::cout << "Pointer to const has an address of: " << static_cast<const void*>(pointer_to_const) << " and value of: " << *pointer_to_const << std::endl; pointer_to_const = &c; std::cout << "Pointer to const has a new address of: " << static_cast<const void*>(pointer_to_const) << " and value of: " << *pointer_to_const << std::endl; std::cout << std::endl; }
运行输出
-------Constant Pointer---------(works as expected)
Constant pointer a has an address of: 0x7ff7b1bc749f and value of: a
Constant pointer a has an address of: 0x7ff7b1bc749f and a new value of: x--------Pointer to Const--------(not sure why I don't get a new address for c)
Pointer to const has an address of: 0x7ff7b1bc7488 and value of: b
Pointer to const has a new address of: 0x7ff7b1bc7488 and value of: c--------Pointer to Const--(CORRECTED OUTPUT BASED ON USER FEEDBACK)
Pointer to const has an address of: 0x7ff7b54a844e and value of: b
Pointer to const has a new address of: 0x7ff7b54a844d and value of: c
问题解答
疑问1:地址未更新的假象
你最初看到地址没变化,是因为代码修改前没有对pointer_to_const做正确的类型转换。const char*类型的指针直接用cout输出时,会被当作C风格字符串处理,而非输出内存地址。你后来添加的static_cast<const void*>(pointer_to_const)才是正确写法——将指针转换为void*类型后,cout才会输出它指向的内存地址。
从修正后的输出可以看到,转换类型后,pointer_to_const指向b和c的地址确实不同(0x7ff7b54a844e和0x7ff7b54a844d),说明c有唯一的内存地址,只是之前的输出方式错误导致了误解。
疑问2:无法直接显示&b/&c的原因
&b和&c的类型是char*(或const char*),和pointer_to_const一样,直接用cout输出时会被解析为字符串指针。如果b或c所在内存后没有终止符\0,cout会持续输出内存内容直到遇到\0,导致乱码或错误,而非输出地址。
正确的做法是将它们强制转换为void*类型,示例代码如下:
std::cout << "Address of b: " << static_cast<void*>(&b) << std::endl; std::cout << "Address of c: " << static_cast<void*>(&c) << std::endl;
而&pointer_to_const是指针自身的地址,类型为const char**,不会被cout当作字符串处理,所以能直接输出地址。
关键知识点
char*/const char*类型指针,cout默认按C风格字符串输出,而非内存地址;- 要输出指针的内存地址,必须强制转换为
void*类型; - 指向常量的指针(
const char*)可修改指向,与常量指针(char* const,不可修改指向)是完全不同的概念。
内容的提问来源于stack exchange,提问作者Stevo

