1

I'm trying to insert data into a Data struct first, then parse it to an insertFirst function that can put it into my linked list. This is all done in a while loop.

while(fgets(line, 8, file) != NULL)
{
    x= (Data*)malloc(sizeof(Data)); 
    sscanf(line, "%s %s", line, val);

    x->c = line; 
    x->v =val; 

    insertFirst(list, x);
}

However I'm trying to reuse the Data struct. Mallocing it every time. The problem I have is that despite the lines being read in correctly. e.g. LOREM 1 and IPSUM 3, the linked list will always contain IPSUM 3. How do i use a struct like this repeatedly in the loop?

Kevin
  • 43
  • 1
  • 7

2 Answers2

4

The problem here is you are assigning cmd and val as pointers to x->command and x->value, hence x->command and x->value will always points to updated value in cmd and val.

So you change the code as below.

while(fgets(line, 15, inputFile) != NULL)
{
    x= malloc(sizeof(Data)); 
    sscanf(line, "%s %s", cmd, val);

    x->command = strdup(cmd); 
    x->value = strdup(val); 

    insertFirst(list, x);
}

Where strdup calculates the space needed and allocates the memory dynamically and copies the input string and returns the newly allocated pointer.

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
0

Another possibility is this:

typedef struct Data
{
    char command[100]; 
    char value[100]; 
} Data; 

while(fgets(line, 15, inputFile) != NULL)
{
    x= (Data*)malloc(sizeof(Data)); 
    sscanf(line, "%s %s", x->command, x->value);  

    insertFirst(list, x);
}

Disclaimer: no erro checking or bounds checking for the strings is done here for brevity.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115