Assignment of string to structure element

后端 未结 5 1942
长情又很酷
长情又很酷 2021-01-22 22:50

My program crashes when I try to assign a string value to a member of a structure. My suspicion is that the member (of type string) within the structure was never properly alloc

相关标签:
5条回答
  • 2021-01-22 23:25

    The way you are allocating node is incorrect: if you want to dynamically allocate non-POD types in C++, you need to use new, since it will call the required constructors (followed by a call to delete when appropriate).

    But it might be simpler to allocate an automatic instance:

    DataRow node;
    

    If you do need a pointer, make sure to have a look at smart pointers, particularly std::unique_ptr and std::shared_ptr. See also boost::scoped_ptr.

    0 讨论(0)
  • 2021-01-22 23:33

    You have to create a new struct and not use malloc at all.

    So use:

    DataRow* node = new DataRow;
    

    you should also take care of cleaning it up like so:

    delete node;
    

    and in case you don't want to allocate it from the heap you can do this as well:

    DataRow node;
    
    0 讨论(0)
  • 2021-01-22 23:37

    In C++ use 'new' instead of 'malloc'. Using malloc does not run the constructor of your class, so the string is not initialized.

    0 讨论(0)
  • 2021-01-22 23:43

    malloc doesn't ensure any constructors of the members of your struct are called. In C++ struct is basically the same as class, the only difference is that members are public by default rather than private. So you should new the object/struct, and delete it when done.

    0 讨论(0)
  • 2021-01-22 23:43

    So before I get to answering your question I just wanted to say that you should not use Malloc in c++ unless you are forced to. This answer explains why fairly well.

    In what cases do I use malloc vs new?

    With that said changing this line

    DataRow* node = (DataRow*)malloc(sizeof(DataRow));
    

    To this

    DataRow* node = new DataRow;
    

    Will fix your problem

    0 讨论(0)
提交回复
热议问题