My goal is to write a function that adds an object of the AccountInfo class to a 200-element array of AccountInfo objects. The array starts with no objects in it. The AccountInfo class contains several fields - mostly char*, with a few ints.
After hours of attempts, I cannot figure out what is going wrong. My code all complies, but I get an exception
First-chance exception at 0x00A164B0 in Project1.exe: 0xC0000005: Access violation writing location 0x00000000.
on the following line:
getAccounts()[size()] = AccountInfo(*newUser);
I've simplified my code as much as I can while retaining the essential information. If supplying the code for the AccountInfo class would be helpful, I can do that too.
#include <iostream>
using namespace std;
class AccountInfo
{
private:
char* _userLoginName;
char* _password;
unsigned int _uid;
unsigned int _gid;
char* _gecos;
char* _home;
char* _shell;
public:
//Constructor and Destructor
AccountInfo(char* username);
~AccountInfo();
//Also contains getters and setters.
};
//Method Definitions
AccountInfo::AccountInfo(char* username)
{
//Initialize the username and other mandatory fields.
_userLoginName = username;
_home = "/", "h", "o", "m", "e", "/", username;
_shell = "/bin/bash";
}
AccountInfo::~AccountInfo()
{
//Delete dynamically created fields.
delete _userLoginName;
delete _password;
delete _gecos;
delete _home;
delete _shell;
}
class UserDB
{
private:
AccountInfo* _accounts[200];
unsigned int _size;
unsigned int _nextUid;
unsigned int _defaultGid;
AccountInfo* getAccounts();
public:
UserDB();
~UserDB();
void adduser(AccountInfo* newUser);
int size(); // return the number of accounts stored (_size)
};
AccountInfo* UserDB::getAccounts()
{
return _accounts[200];
}
UserDB::UserDB()
{
_size = 0;
_nextUid = 1001;
_defaultGid = 1001;
}
int UserDB::size()
{
return _size;
}
void UserDB::adduser(AccountInfo* newUser)
{
getAccounts()[size()] = AccountInfo(*newUser);
}
int main() //main method
{
UserDB users;
AccountInfo *x = new AccountInfo("Joe");
//This creates an AccountInfo object with one of its
//char* fields initialized to "Joe".
users.adduser(x);
return 0;
}
What am I doing wrong? How can I fix it?