String in struct

25,453

Solution 1

C++ is not C.

You shouldn't #include anything from the bits folder.

You should not use malloc to allocate memory. You should use new instead:

node* p = new node();

Or just don't dynamically allocate memory at all:

node p;

C++ is not C.

Solution 2

Don't use malloc: the constructor for std::string will not be called and so the object created will be in an undefined state.

Use new instead. The C++ runtime will then call the default constructor for the std::string member. Don't forget to match the new with a delete.

Solution 3

You forget to declare str. Also, don't use new (and certainly not malloc!!!) unless you have to (read: never):

#include <iostream>
#include <string>

using namespace std;
struct node {
    std::string a;
};
int main()

{
    std::string str;

    cout << str << endl;

    node p;
    p.a = "a";
    cout << p.a;
}
Share:
25,453
akshita007
Author by

akshita007

Updated on July 09, 2022

Comments

  • akshita007
    akshita007 almost 2 years
    #include <bits/stdc++.h>
    
    using namespace std;
    
    struct node
    {
        std::string a;
    };
    
    int main()
    {
        cout << str << endl;
        struct node* p = (struct node*)(malloc(sizeof(struct node)));
        p->a = "a";
        cout << p->a;
        return 0;
    }
    

    The above code produces a runtime error. The struct is working for ints but when I try to use string as its member variable, error occurs. It also gives runtime error on codechef ide.