#include <iostream>
using namespace std;
 
struct account
{
    account();
    int accountnum;
    float balance;
    float interestrate;
};
 
account::account()
{
    accountnum = 50;
}
 
struct account2
{
    account2();
    account * data;
    void test();
};
 
account2::account2()
{
}
 
void account2::test()
{
    data->accountnum = 1000;
}
 
int main()
{
    account test;
    account2 test2;
    cout << test.accountnum << endl;
    test2.test(); //Error
    cout << test.accountnum << endl;
    return 0;
}

I have the following code. It contains two structs, account and account2.

I want to change the value of accountnum of account using a pointer in account2. However when I run the program it will keep on crashing. Please tell me what is wrong with this code and how I could fix it.

your data pointer is never set to point to anything. You could set it before line 38, then you wont get your error. So say on line 37, put test2.data = &test;, then you will no longer get an error.

Thank you for your helpful reply. Is it possible to have it work inside the struct though?

There are multiple ways you could do it, but the bottom line is you have to set your data pointer to actually point to something before you can use it(or make a "new" object), otherwise you can't do anything with it. You could make a function in your struct that takes an address as a parameter, and then set the pointer by calling the function, or you could make a constructor that takes an account parameter, and set the data pointer in your constructor. It really depends on what is best for what you are trying to accomplish.

Good luck and have fun, c++ is quite the undertaking, but once you get good with it, the sky's are the limit! =p

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.