简体   繁体   English

C ++:通过指针访问struct的成员

[英]C++: Access members of struct via a pointer

I run in to segmentation faults when running this code (no compiler warnings or errors). 运行此代码时遇到段错误(无编译器警告或错误)。 It occurs when trying to assign "Test" to str->sString 尝试将“测试”分配给str->sString

MyClass.cpp
//Constructor
MyClass::MyClass( MyStruct *pDesc )
{   
    pDesc = new MyStruct();

    //This is where I get a segmentation fault  
    pDesc->bar= 0xFF;   

}


MyClass.hpp

class ClGadgetFs
{
    public:
            struct MyStruct{
        int bar;
        };
       MyClass(MyStruct *pDesc = NULL);
};

I thought when calling new I would be aalocating memory for the struct? 我以为在调用new时会为该结构增加内存? Like malloc(sizeof(myStruct)) Where am I wrong? malloc(sizeof(myStruct))我哪里错了?

void setStruct(myStruct *str)
{
   str->sString = "Test";
   str->nNo = 4;
}

int main()
{
    myStruct p;
    setStruct(&p);
    return 0;
}

you can do this instead 你可以这样做

Edit 编辑

int main()
{
   MyStruct *pDesc;
   MyClass myClassInstance( pDesc );
   std::cout<< pDesc->bar << std::endl;
   return 0;
}

and

MyClass::MyClass( MyStruct *pDesc ) 

should be changed to 应该更改为

MyClass::MyClass( MyStruct *& pDesc )
void setStruct(myStruct*& str)

以上可能就是您想要的:更改传递的指针作为输出参数。

#include <string>

struct myStruct
{
   std::string sString;
   int nNo;
};


void setStruct(myStruct **str)
{
   *str = new myStruct();
   (*str)->sString = "Test";
   (*str)->nNo = 4;
}

int main()
{
    myStruct *p;
    setStruct(&p);
}

should be what you want, this is the C-style of passing the pointer; 应该是您想要的,这是传递指针的C样式; since you're allocating memory for the passed pointer, passing the pointer alone doesn't work, you should pass the pointer's address. 由于您要为传递的指针分配内存,因此仅传递指针是行不通的,因此应传递指针的地址。 Another way would be a reference to the pointer that Joop Eggen's answer points out. 另一种方法是引用Joop Eggen的答案指出的指针。

str in the function setStruct is a local variable, whose life time is limited in this function. str在功能setStruct是一个局部变量,它的续航时间在这个功能是有限的。

So when new returns the address, there is no effect on the actual parameter. 因此,当new返回地址时,对实际参数没有任何影响。 It is just the same to 就是一样

void func(int a){
     a = 4
}

You should use pointer to pointer or reference 您应该使用指向指针或引用的指针

void setStruct(myStruct ** str){
    (*str) = new myStruct();
    (*str)->sString = "Test";
    (*str)->nNo = 4;
}

void setStruct(myStruct *& str){
    str = new myStruct();
    str->sString = "Test";
    str->nNo = 4;
}

It's likely that the caller of setStruct is allocating a myStruct on the stack : setStruct的调用者很可能在堆栈上分配了myStruct

myStruct value;

and you are calling setStruct(&value); 并且您正在调用setStruct(&value);

That would cause the segmentation fault as you would be attempting to rearrange the stack memory. 这将导致分段错误,因为您将尝试重新排列堆栈存储器。 It's difficult to say anything else without the complete example though. 如果没有完整的示例,很难说出其他任何话。

There's nothing wrong with the code as it stands aside from the fact that the value of the pointer following str = new myStruct(); 该代码没有任何问题,因为它位于str = new myStruct();之后的指针值str = new myStruct(); is not passed back to the caller: the caller would be still referring to the pointer pointing to unallocated memory which would result in undefined behaviour . 没有传递回调用者:调用者仍将指向指向未分配内存的指针,这将导致未定义的行为 But that is not causing your crash since given where you say the error happens. 但是自从给出错误发生的位置以来,这不会导致崩溃。

A simple fix would be to change the function prototype to 一个简单的解决方法是将函数原型更改为

void setStruct(myStruct*& str)

ie pass the pointer by reference so the caller get's the modified pointer value back. 即通过引用传递指针,以便调用者将修改后的指针值返回。

You should use a reference to your pointer to modify it in your function: 您应该使用对指针的引用在函数中对其进行修改:

struct myStruct{
    std::string sStrnig;
    int nNo;
};


void setStruct(myStruct* &str){

    str = new myStruct();

    str->sString = "Test";
    str->nNo = 4;
}

main(){
    struct myStruct *str = 0;
    setStruct( str );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM