Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String in struct [duplicate]

Tags:

c++

string

struct

#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.

like image 636
akshita007 Avatar asked Oct 23 '25 09:10

akshita007


2 Answers

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.

like image 176
TartanLlama Avatar answered Oct 24 '25 22:10

TartanLlama


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;
}
like image 30
sehe Avatar answered Oct 24 '25 23:10

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!