指针分配说明
Pointer Assignment Clarification
仍在学习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"生活在转储中!然后它崩溃了。
相关文章:
- 将数组的地址分配给变量并删除
- vector.resize()中的分配错误
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- Win32编译器选项和内存分配
- 函数中堆分配的效果与缺少堆分配的情况
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 获取字符串的长度并将其分配给数组
- 将地址分配给本地指针后,公共对象的变量将消失
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- 我在二维向量中是否正确分配了内存
- 正在尝试重载二进制搜索树分配运算符
- 当使用通配符和null指针调用函数时,对输出的说明
- GlobalAlloc而不是其他分配方法
- C++指针分配说明
- 分配运算符实现的说明
- 指针分配说明
- 正在复制分配增压选项_说明
- 动态分配的内存存储说明