[英]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-> ....访问。
player1
must be of type Pokemon
as it gets its value from the function summon
that return a Pokemon
player1
的类型必须为Pokemon
,因为它从函数获取其值summon
返回一个Pokemon
p1
is of type Pokemon *
(aka Pokemon pointer) p1
是Pokemon *
(又名Pokemon指针)的类型
and you do player1 = p1;
然后你做
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. 似乎发生的情况是,您用指针变量覆盖了一部分字符串
name
,从而破坏了字符串值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.