Home > Back-end >  Why a member of an array of struct has always the same value?
Why a member of an array of struct has always the same value?

Time:12-03

So i wanna read a text file and populate an array of structs with the values of the file

this is my file:

tile1;1;1;1;0
tile2;0;1;1;1
tile3;1;0;1;1
tile4;1;1;0;1
tile5;1;0;1;0
tile6;0;1;0;1
tile7;1;1;0;0
tile8;0;1;1;0
tile9;0;0;1;1
tileX;1;0;0;1

and this is my code

FILE *file;

struct tile
{
    char * file_name;
    int l,u,r,d;
};
typedef struct tile tile_t;
tile_t tileData[10];

int main(void)
{
    #define BIG 1000
    char str[BIG];

    if ((file = fopen("res/tiles.conf", "r")) != NULL)
    {
        char* item;
        int i = 0;
        while (fgets(str, BIG, file) != NULL)
        {
            int j = 0;
            for (item = strtok(str, ";"); item != NULL; item = strtok(NULL, ";"))
            {
                //printf("%d item %s\n", j, item);
                switch (j) {
                    case 0: tileData[i].file_name = item;
                        break;
                    case 1: sscanf(item, "%d", &tileData[i].l);
                        break;
                    case 2: sscanf(item, "%d", &tileData[i].u);
                        break;
                    case 3: sscanf(item, "%d", &tileData[i].r);
                        break;
                    case 4: sscanf(item, "%d", &tileData[i].d);
                        break;
                }
                j  ;
            }
            i  ;
        }

        fclose(file);
        
        for (int k = 0; k < 10; k  )
        {
            printf("index:%d name:%s l:%d u:%d r:%d d:%d\n", k, tileData[k].file_name, tileData[k].l, tileData[k].u, tileData[k].r, tileData[k].d);
        }
    }

    return 0;
}

the print loop at the end shows me that the int values are correct, while the file name member has always the value of the last row of the file

index:0 name:tileX l:1 u:1 r:1 d:0
index:1 name:tileX l:0 u:1 r:1 d:1
index:2 name:tileX l:1 u:0 r:1 d:1
index:3 name:tileX l:1 u:1 r:0 d:1
index:4 name:tileX l:1 u:0 r:1 d:0
index:5 name:tileX l:0 u:1 r:0 d:1
index:6 name:tileX l:1 u:1 r:0 d:0
index:7 name:tileX l:0 u:1 r:1 d:0
index:8 name:tileX l:0 u:0 r:1 d:1
index:9 name:tileX l:1 u:0 r:0 d:1

I'm not an experienced C dev but I have done similar programs in the past and this has never happened

CodePudding user response:

The problem is that you don't reserve space for the string filename, in consequence you write again and again to the same address.

Switch from

case 0: tileData[i].file_name = item;

to

case 0: tileData[i].file_name = strdup(item);

Check how to implement strdup if it is not available: Implementation of strdup() in C programming

  • Related