gpt4 book ai didi

c - 为什么编译器会发出 : warning: assignment makes integer from pointer without a cast

转载 作者:太空宇宙 更新时间:2023-11-04 01:16:09 25 4
gpt4 key购买 nike

我正在尝试将一些信息放入二维字符数组中。我在 stdin 中放入了一个名称列表,我试图将其放入一个数组中,其中的数字对应于字符数组(名称)。出于某种原因,当我尝试打印名称时,它会输出一些随机字符。

 #include <stdio.h>
#define NAME_MAX_LENGTH 20
#define NUM_MIN_PLAYERS 2
#define NUM_MAX_PLAYERS 20

struct PlayerList {
unsigned int num_players;
char name[NUM_MAX_PLAYERS][NAME_MAX_LENGTH + 1];
};

int main() {
int num;
char nom[NAME_MAX_LENGTH + 1];
struct PlayerList player;

while(fgets(nom, sizeof nom, stdin) != NULL){
char longueur = 0;
player.name[num++][sizeof nom] = nom;
printf("%d:%s\n", num, player.name[num]);
}
player.num_players = num;


return 0;
};

最佳答案

这个声明

player.name[num++][sizeof nom] =  nom;

不正确。

至少你是说

strcpy( player.name[num++], nom );

为此你需要包含标题

#include <string.h>

否则表达式

player.name[num++][sizeof nom]

的类型为 char,而右侧表达式 nom 的类型为 char *

也是这个输出

printf("%d:%s\n", num, player.name[num]);

有未定义的行为,因为变量 num 已经在上面的语句中增加了

player.name[num++][sizeof nom]
^^^^^

你至少应该写

printf("%d:%s\n", num - 1, player.name[num-1]);

关于c - 为什么编译器会发出 : warning: assignment makes integer from pointer without a cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58558331/

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