指针分配说明

Pointer Assignment Clarification

本文关键字:说明 分配 指针      更新时间:2023-10-16

仍在学习C++。试图了解一些关于指针分配的内容。我的问题在下面代码的注释中。

#include <string>
#include <iostream>
int main(){
    std::string test = "foop";
    std::string * pointer;
    *pointer = test;       //Why does this crash my program...
    pointer = &test;    //But this doesn't? 
    return 0;
}

根据我读到的内容,我认为*p=o和p=&o也做了同样的事。我很感激你的启示。

谢谢!

*p = o;

o分配给p所指向的对象。在您的代码中,p(或pointer)未初始化,所以它会分配给天知道的东西,导致崩溃(如果幸运的话),或者默默地损坏内存(如果不是)。

p = &o;

o的地址分配给p,使p指向o。这是明确定义的。

指针需要首先分配地址,以便取消引用。现在string*指针指向一个垃圾地址!因此,当您分配字符串foo时,程序会说,我不希望"foo"生活在转储中!然后它崩溃了。