0

I need to get name from the file (string).

But certainly it gets (null) value.

void dealer__init(){
    FILE * dealer = fopen(DEALER_L, "r");
    fscanf(dealer, "%d  %d  %255s", &my_og.money, &my_og.check_ok, my_og.name);
    printf("%255s\n", my_og.name);
    printf("%d\n", my_og.money);
    printf("%d\n", my_og.check_ok);
    
    if(money_at_beg == true && my_og.check_ok == 0){
        my_og.money = MONEY_AT_BEG_INT;
        my_og.check_ok = 1;
        dealer__save();
    }
    printf("My name is set to: %s", &my_og.name);
    fclose(dealer);
}

My file:

3000  1  dimitar

My struct:

struct dealer{
    int money;
    int check_ok;
    char *name;
}my_og;

1 Answers1

3

You can't use the fscanf function (or most other functions)1 to read data into an uninitialized – or invalid – pointer. That causes undefined behaviour which, in your case, appears to go unnoticed until you try to print out the value after the attempted read. (This is one of the nastier aspects of UB: that the code appears to work.)

You need to either explicitly allocate some memory to which your pointer refers to, like this:

my_og.name = malloc(256); // Allocate some memory

Or, perhaps simpler, declare the name member as a fixed-size array, rather than a pointer:

struct dealer{
    int money;
    int check_ok;
    char name[256]; // 'allocated' when the structure is declared
}my_og;

1 There is, I believe a non-standard (POSIX) version of the scanf formatting option (%ms) that automatically allocates memory, but I would personally avoid such things like the plague. See: scanf dynamic allocation.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83