gpt4 book ai didi

c - 从不兼容的指针类型和结构数组进行初始化

转载 作者:太空宇宙 更新时间:2023-11-04 06:03:04 26 4
gpt4 key购买 nike

我目前正在学习 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.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 实例放入一个包含三个 pokemon 的数组中。到目前为止,我得到了这个:

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 );

但这并不想编译 - 我想这是另一个指针错误。

最佳答案

Pokemon p[3];
...
Pokemon poke;
strncpy(poke.nickname, nickname, sizeof(poke.nickname));
strncpy(poke.type, type, sizeof(poke.type));
poke.level = level;
p[i] = poke;

编辑:修复临时结构初始化。

关于c - 从不兼容的指针类型和结构数组进行初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15633172/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com