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?

6
  • 1
    How is val declared? Commented Oct 5, 2018 at 6:43
  • 1
    you're not reusing the struct. You're just assigning pointers pointing to the same character array all over. Consider having command and val as array members in the Data and sscanfing directly to these instead. Commented Oct 5, 2018 at 6:43
  • Also don't cast malloc Commented Oct 5, 2018 at 6:44
  • Also, sscanf can fail Commented Oct 5, 2018 at 6:45
  • What is Data? Commented Oct 5, 2018 at 6:49

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you! Saw what I was doing wrong, needed to allocate memory for command and value. And your use of strdup was more better than my extra mallocs.
@KevinLe strdup does internally the same thing.
Was just neater than what i had.
@KevinLe Yes for sure.
@Kevin Please note though that strdup is not standard C, so it isn't portable.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.