【问题标题】:C++ duplicating a pointerC ++复制指针
【发布时间】:2016-02-26 05:13:41
【问题描述】:

我无法弄清楚复制指针的语法。

我将如何制作theVar2=theVar

Struct MyStructureType {
    double* theVar2;
}

MyStructureType* myStruct;
double* theVar;

theVar = malloc(sizeof(double));


myStruct->theVar2 = theVar; //segfaults

【问题讨论】:

  • 为什么在 C++ 中使用malloc() 而不是new
  • 请发帖MCVE。您确定在实际代码中分配了一些有效的缓冲区并将其地址分配给myStruct
  • 在 C++ 中 a->b 表示 (*a).b,因此这里由于 myStruct 未初始化,因此会出现段错误。

标签: c++ pointers structure


【解决方案1】:

先给MyStructureType分配内存,然后在里面使用data member

MyStructureType* myStruct = new MyStructureType();
double* theVar = new double();
myStruct->theVar2 = theVar;

【讨论】:

    【解决方案2】:

    在使用它的值之前,您必须将变量设置为某个合理的值。您尚未将 myStruct 设置为任何合理的值。所以暂时不要使用。

    您还没有任何theVar2 实例。它是结构的成员,但该结构的实例尚不存在。你可以这样做:

    MyStructureType myStruct;
    myStruct.theVar2 = theVar;
    

    一旦MyStructureType 的实例存在,您就可以设置它的theVar2 成员。

    【讨论】:

      【解决方案3】:

      您需要先初始化myStruct,然后才能间接通过它。

      MyStructurType *myStruct = new MyStructureType;
      

      【讨论】:

        【解决方案4】:

        关于您的代码的几点:

        1. malloc 的错误用法:malloc 返回一个 void *,在使用它之前,你应该总是这样转换它:

          double *myptr = (double*) malloc(sizeof(double));

        2. 在初始化之前尝试使用myStruct:您已将myStruct 声明为指向您的结构的指针,您需要在使用它之前对其进行初始化。您的代码应如下所示:

        在这里使用malloc,您可以/应该使用new。其他答案已经证明了这一点。

        Struct MyStructureType {
                double* theVar2;
            }
        
        MyStructureType* myStruct;
        double* theVar;
        
        myStruct = (MyStructureType*) malloc(sizeof(MyStructureType));
        theVar = (double*) malloc(sizeof(double));
        
        myStruct->theVar2 = theVar;
        

        【讨论】:

        • 哦,呵呵。 #2 有道理。谢谢
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-25
        相关资源
        最近更新 更多