b.g.
b.g.

Reputation: 850

codeblocks c++ stops working may be due to referencing

//in header file(in User class):
int howManyOpponents =0;
User** userArray; //(which is initialized to userArray = new User*[5] in the constructor)

//in class file:
void User::addWin(User* aUser)
{
    userArray[howManyOpponents] =aUser;
    howManyOpponents++;
}

//in main file
int maximumUser = 20;
User* userList[maximumUser];
(*userList[i]).addWin(userList[j]);

codeclocks stops working, I've traced the problem to the User::addWin and tried many different referencing or pointing settings but couldn't handle it. There may be a simple bug. Thank you.

Upvotes: 0

Views: 94

Answers (3)

nikau6
nikau6

Reputation: 961

Here's a example about how to use arrays of pointers:

    size_t maxUsers = 5;
    size_t maxUserLen = 48;
    char** UserList = 0;

    // First, allocates a array of pointers
    UserList = new char*[maxUsers];

    // Second, allocates each pointers in the array of pointers
    for(size_t i=0; i<maxUsers; i++)
    {
        UserList[i] = new char[maxUserLen];
        memset(UserList[i], 0, maxUserLen);
    }

    // Add user
    const char* user1 = "Mike";
    const char* user2 = "James";

    strcpy(UserList[0], user1); // First element in the list
    strcpy(UserList[1], user2); // Second element in the list, etc...

Upvotes: 0

Przemek
Przemek

Reputation: 1

Consider passing argument by reference instead of passing them by pointers. Try to avoid using raw poiters in your code. If you really need pointers, think about using smart pointers.

Upvotes: 0

Unimportant
Unimportant

Reputation: 2096

User* userList[maximumUser];

Creates an array of maximumUser User pointers. No actual instances of User are constructed.

You then try to call a method with one of these uninitialised pointers, causing the crash:

(*userList[i]).addWin(userList[j]);

To fix, create an array of actual User instances (assuming User's constructor does not require arguments):

User userList[maximumUser];
userList[i].addWin(userList[j]);

Upvotes: 1

Related Questions