我现在正在学习 C 语言,在理解指针和结构数组时遇到了一些麻烦。这是我编写的一个简单程序:
#include <stdio.h>
typedef struct { /* Define the structure Pokemon that contains a nickname, type and level*/
char nickname[11];
char type[11];
int level;
} Pokemon;
int main(void) {
char nickname[11];
char type[11];
int level;
for (int i = 0; i < 3; i++) { /* Iterate through the loop three times, each time create a new pokemon */
printf("Pokemon %i \n", i);
printf("Nickname: ");
scanf("%s", &nickname);
printf("Type: ");
scanf("%s", &type);
printf("Level: ");
scanf("%i", &level);
Pokemon * poke = {nickname, type, level}; /* Insert the pokemon into the array of Pokemon */
printf("%s, %s, %i", poke->nickname, poke->type, poke->level);
}
}
基本上我想为具有三个特征的口袋妖怪创建一个结构。在主函数中,我希望用户输入 3 个 pokemon 的特征,然后创建一个具有这三个特征的 struct pokemon 实例,并将这些特征打印到 stdout。使用此代码,它可以编译,但我收到警告:
pokemon.c:33:9: warning: initialization from incompatible pointer type [enabled by default]
pokemon.c:33:9: warning: (near initialization for ‘poke’) [enabled by default]
pokemon.c:33:9: warning: excess elements in scalar initializer [enabled by default]
pokemon.c:33:9: warning: (near initialization for ‘poke’) [enabled by default]
pokemon.c:33:9: warning: excess elements in scalar initializer [enabled by default]
pokemon.c:33:9: warning: (near initialization for ‘poke’) [enabled by default]
不知道为什么会这样——我想这与我设置的指针有关,但正如我所说,我仍在努力解决这个问题。
我还想将每个口袋妖怪实例放入三个口袋妖怪的数组中。到目前为止,我有这个:
Pokemon p [3];
// This bit inside the for loop and after the 'poke' struct instantiation
p[i] = poke;
printf("%s,%s,%i inserted\n", poke.nickname, poke.type, poke.level );
但这不想编译 - 我想这是另一个指针错误。