我正在努力学习C++,我在理解为什么我的指针在被重新分配给一个新的字符变量后没有显示预期的地址值时遇到了一些问题。
在所提供的代码中,我希望
pointer_to_const = &c;
显示一个新的地址值,从它被分配给字符变量b
开始
当我运行下面显示的代码时,我得到这个;
-------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 = &c
后,我不明白为什么当我用cout
显示pointer_to_const时,看不到新地址。c
没有唯一的地址吗?
另外,在Pointer to Const部分,我可以显示&pointer_to_const
和cout
,但我不能正确显示&b
,或者直接显示&c
和cout
。
我非常关注这个的C版本,我正试图让它在C++中工作,作为整个学习过程的一部分。
https://www.youtube.com/watch?v=egvGq3WSF9Y
#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;
std::cout << "Pointer to const has an address of: " << &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: " << &pointer_to_const << " and value of: " << *pointer_to_const << std::endl;
std::cout << std::endl;
}
1条答案
按热度按时间bbuxkriu1#
当写入
&pointer_to_const
时,您将获得指针的地址。这与指针包含/指向的地址不同。