1

I'm trying to put some information into a 2d char array. I'm putting a list of names in stdin that i'm trying to put into an array with a number corresponding to the array of characters(names). For some reason, when I try to print the names, it output some random characters.

 #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;
};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

4

This statement

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

is incorrect.

At least you mean

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

To do so you need to include header

#include <string.h>

Otherwise the expression

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

has the type char while the right side expression nom has the type char *.

Also this output

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

has undefined behavior because the variable num was already incremented in the statement above

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

You should write at least

printf("%d:%s\n", num - 1, player.name[num-1]);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335