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

标签 c arrays struct c-strings strcpy

我正在尝试将一些信息放入二维字符数组中。我在 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/

相关文章:

python - 在python opencv中,为什么array [:]和array不同?

c++ - 为什么 C 和 C++ 支持在结构中按成员分配数组,但通常不支持?

c - 如何从结构中读取数据指针?

c - C程序中的指针

c - size 和 objdump 报告文本段的不同大小

终端应用程序上的 Cocoa UI

javascript - 在 javascript 中,如何删除之前单击的同级 div,以便一次只显示一个答案?

c++ - 带有 const 表达式的数组声明

c++ - 从循环添加到结构 (c++)

无法在结构数组中正确追加元素