c++ 如何确认指针已被重新分配到新地址-指向常量字符的指针

9nvpjoqh  于 2023-05-24  发布在  其他
关注(0)|答案(1)|浏览(237)

我正在努力学习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_constcout,但我不能正确显示&b,或者直接显示&ccout
我非常关注这个的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;
}
bbuxkriu

bbuxkriu1#

当写入&pointer_to_const时,您将获得指针的地址。这与指针包含/指向的地址不同。

&pointer_to_const //address of the pointer
pointer_to_const  //content of the pointer (i.e. an address of another variable)
*pointer_to_const //content of the variable that the pointer points to

相关问题