简体   繁体   中英

Why does my pointer to struct forget strings?

In my main functions I have two players which are represented by structs with data, including names. When in another source file I create a pointer to these structures, I am unable to access the name strings, whereas the rest of the data is fine.

//In pokemonList.c
typedef struct{

    char name[20];
    int level;
    int health;
    int type;
    int type2;


    int fainted;


    int moves[4];

    //stats
    int hp;
    int attack;
    int defense;
    int spAttack;
    int spDefense;
    int speed;

    int attackStage;
    int defenseStage;
    int spAttackStage;
    int spDefenseStage;
    int speedStage;

    int spriteNo;

}Pokemon;

Pokemon summon(Pokemon pokemon, int level){
    pokemon.level = level;
    pokemon.health = (int)((((2.0 * (double)pokemon.hp) + 31.0) * (double)level)/100.0) + (double)level + 10.0;
    pokemon.attack = levelUp(pokemon.attack, pokemon.level);
    pokemon.defense = levelUp(pokemon.defense, pokemon.level);
    return pokemon;
}

//In main.c
player1 = summon(venusaur, 50);
player2 = summon(blastoise, 100);

initialiseGUI(&player1, &player2);

//In video.c

void initialiseGUI(Pokemon *p1, Pokemon *p2){

    strcpy(player1name, p1->name);
    strcpy(player2name, p2->name);
    printf("p1->name: %s\n", p1->name);
    player1 = p1;
    player2 = p2;

    printf("p1->name: %s\nplayer1->name: %s\n", p1->name, player1->name);
}

I expected the output of this to be:

p1->name: Venusaur

p1->name: Venusaur

player1->name: Venusaur

Actual output:

p1->name: Venusaur

p1->name:

player1->name:

all the other data in the struct is accessible from player1->....

player1 must be of type Pokemon as it gets its value from the function summon that return a Pokemon

p1 is of type Pokemon * (aka Pokemon pointer)

and you do player1 = p1;

In other words - you assign a "Pokemon pointer" to a "Pokemon" which is invalid.

What seems to happen is that you overwrite part of the string name with the pointer variable and thereby destroy the string value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM