Reputation: 458
Basically I have this code:
#include <iostream>
using namespace std;
struct foo{
string *question;
//other elements
};
int main(){
foo *q;
foo *q2;
q->question = new string("This is a question");
//q2->question = new string("another question");
}
and when I uncomment q2->question = new string("another question");
it errors and I have no idea why.
Update:
the error is a windows message saying the program has stopped working and it prints Process exited with return value 3221225477
Upvotes: 0
Views: 76
Reputation: 21
You didn't allocate memory for q
and q2
.
Replace
foo *q;
foo *q2;
with
foo *q = new foo();
foo *q2 = new foo();
At the end, delete all created objects:
delete q->question;
delete q;
delete q2->question;
delete q2;
Upvotes: 1
Reputation: 96810
foo *q;
foo *q2;
You're getting Undefined Behavior when using indirection on these pointers because these pointers have not been initialized (i.e. they are not pointing to a valid address).
You need to have them point to an object:
foo* q = new foo();
foo* q2 = new foo();
// don't forget to delete
or just use stack-allocation:
foo q;
foo q2;
q.question = "This is a question";
Upvotes: 1
Reputation: 4275
Your q
and q2
pointers are uninitialized. You're trying to access memory which you haven't allocated. As a short term fix:
int main(){
foo *q = new foo;
foo *q2 = new foo;
q->question = new string("This is a question");
q2->question = new string("another question");
// don't forget to release the memory you allocate!
delete q->question;
delete q2->question;
delete q;
delete q2;
}
A better solution in this case is not to use pointers... there's absolutely no need. Use the stack, and you don't need to deal with pointers, and no need to deallocate.
int main(){
string q1 = "This is a question";
string q2 = "another question";
}
Upvotes: 3