【问题标题】:I am getting a issue in copying a pointer to another pointer in c++我在将指针复制到 C++ 中的另一个指针时遇到问题
【发布时间】:2020-03-17 14:02:42
【问题描述】:

我在第一个代码中遇到分段错误,但第二个代码运行良好,不知道如何?

如何复制指针并将其保存到另一个指针?

#include <iostream>

using namespace std;

int main() {
    int *p;
    int *p1;
    *p1=7;
    p=p1;
    cout<<*p<<" "<<p;
    return 0;
}
#include <iostream>

using namespace std;

int main() {
    int *p1;
    *p1=7;
    int *p=p1;
    cout<<*p<<" "<<p;
    return 0;
}    
//7 0x7ffeea73db70

【问题讨论】:

  • 正如老话所说,“未定义的行为是未定义的”。他们中的一个跑了只是运气不好。
  • 如何为指针pp1 分配内存?!
  • Related: (Why) is using an uninitialized variable undefined behavior? 严格意义上说不是指针,但UB也一样。
  • 即使您没有尝试将7 分配给*p1,这也是未定义的行为。你甚至不能复制一个未初始化的指针,更不用说取消引用它了。
  • @Yksisarvinen:那是 C,不是 C++。基本原理相似,但形式规则不同。

标签: c++ c++11 pointers copy c++14


【解决方案1】:

这两种情况都会调用未定义的行为,在这两种情况下,您都使用未初始化的指针p1,第二种情况对您“有效”的事实纯属运气问题,如您所见here

为了使您的代码有效,您需要通过手动分配内存使其指向有效的内存地址:

int *p1 = new int; //raw pointer, (better to use smart pointers* but let's not get ahead of ourselves).

或者通过为它分配一个有效的int变量的地址:

int i = 5;
int *p1 = &i;

如何复制指针并将其保存到另一个指针?

指针本质上是一个变量,就像任何其他变量一样,您可以像复制普通原始变量一样复制它,实际上,当您执行p = p1 时,您会这样做,这是两个不同的指针,现在将包含相同的值,它们指向的变量的地址。

This code 就是一个例子

#include <iostream>

using std::cout;
using std::endl;

int main() {

    int *p1 = new int;
    *p1 = 7;
    int *p = p1;
    cout<< "Value stored in the address p points to: " << *p << endl  
        << "Value stored in the address p1 points to: " << *p1 << endl
        << "Address where p points to: " << p 
        << " " << endl <<  "Address where p1 points to: "<< p1 
        << endl << "Address of p: " << &p << endl << "Address of p1: "<< &p1;

    return 0;
} 

输出:

Value stored in the address p points to: 7
Value stored in the address p1 points to: 7
Address where p points to: 0x804150 
Address where p1 points to: 0x804150
Address of p: 0x7ffc9447e220
Address of p1: 0x7ffc9447e228

*What is a smart pointer and when should I use one?

【讨论】:

  • 你知道如何复制一个指针并保存到另一个指针吗?
  • @SamareshMaity 我编辑了我的答案来解决你的新问题。
  • @SamareshMaity,很高兴我能提供帮助,如果有正确解决您的问题,请不要忘记 accept one of the answers
【解决方案2】:

当您取消引用 int* 指针时,您承诺在该地址有一个 int 对象。 C++ 相信你,通常是毫无疑问的。但是您从未编写过int a; p1=&amp;a; 或任何其他确保p1 指向实际int 的代码。

事实上,p1 甚至不是空指针。对p1 唯一能做的就是为其分配一个合法值。也就是说,它必须首先出现在作业的左侧。在int* p = p1;右侧不能使用

【讨论】:

    猜你喜欢
    • 2021-02-07
    • 2019-09-27
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多