malachi
malachi

Reputation: 13

Displaying element from pointer struct

I have run onto a little problem and I have looked everywhere but I believe I am looking in the wrong direction. I created an account here in hopes of solving a slight issue I have. I am in the middle of programming an RPG and when I attempt to display one characters "magic spells", I can only display [3]. [0] [1] [2] crashes my game. Game is in C++.

Example of my code below:

Create my struct:

struct Fighter {
    int HP;         //max 999
    int maxHP;
    int MP;         //max 999
    int maxMP;
    int STR;        //max 255
    int CON;        //max 255
    int AGL;        //max 100
    bool dead;
    const char* Magic[]; 
};

Fighter * player = new Fighter[5];

Initializing and assigning elements with these parameters for 4 party members:

void InitPlayer(int pClass, int p)
{
    if(pClass == 0) //Knight
    {
        player[p].maxHP = 750;
        player[p].HP = player[p].maxHP;
        player[p].maxMP = 0;
        player[p].MP = player[p].maxMP;
        player[p].STR = 200;
        player[p].CON = 0;
        player[p].AGL = 35;
    }
    else if(pClass == 1) //Ninja
    {
        player[p].maxHP = 675;
        player[p].HP = player[p].maxHP;
        player[p].maxMP = 0;
        player[p].MP = player[p].maxMP;
        player[p].STR = 175;
        player[p].CON = 0;
        player[p].AGL = 80;
        player[p].Magic[0] = "Cure";
        player[p].Magic[1] = "Haste";
        player[p].Magic[2] = "Sleep";
    }
    //... More Character code
}

Here I draw/print "Magic" to the screen:

Printf_xy(123,223,player[0].Magic[0]);  //Crash
Printf_xy(123,233,player[1].Magic[0]);  //Crash
Printf_xy(123,243,player[2].Magic[0]);  //Crash
Printf_xy(123,253,player[3].Magic[0]);  //Prints "Cure" does not crash

As you can see, it will work but only if I display player[3]. I am sure I am forgetting to do something or initializing something incorrectly. Any help would be greatly appreciated.

Upvotes: 1

Views: 58

Answers (1)

The Dark
The Dark

Reputation: 8514

Magic is a zero length array - when you assign anything into it, or even try to access Magic[0] you are accessing outside of the array boundaries.

If you know the maximum number of magic entries you need, use that as your array size, something like:

const int MagicLimit = 10

...

const char* Magic[MagicLimit]; 

Better still, if you are using c++, use a std::vector to hold the magic strings (also use std::string), that way you can easily tell the length of the list.

For example:

std::vector<std::string> Magic;

Upvotes: 1

Related Questions