This code failed at run time and not at compile time. I am not expert in C++.
Any help?
extern void fn();
int main(int argc, char** argv) {
fn();
}
void fn()
{
struct Foo{
string name;
}*foo;
foo->name="sleiman";
cout<<foo->name<<endl;
}
Why does this code fail at run time and why does it succeed if I create a static instance?
void fn()
{
struct Foo{
string name;
}foo;
foo.name="sleiman";
cout<<foo.name<<endl;
}
foois made to be a pointer but is not initialised so when you try to access name it is reading invalid memory. You initialisefooas a pointer to aFoostruct but do not tell it to point to an actual object so is in effect a loose pointer.In order to make this work you will need to make the pointer point to an actual object by using the
newkeyword or some other means.