yetanotherposter
yetanotherposter

Reputation: 89

C values being remove from linked list after adding them

I would like to understand how come in my linked list are elements in it but they are all empty strings after adding strings to it. It seems like there is some issue when I set the terminating string character but I believe I am making a copy of it and adding the copy to the linked list. This is the code I have.

        char name[256] = " ";
        while (serial.available()) {
            char text= serial.read();
            Print(text);
            if (text== '\n') {
              char copy[256];
              strcpy(copy, name);
               add(copy, list); //adds copy to a linkedlist named list
               name[0] = '\0';
            } else {
                append(name, text);
            }
        }

After function call, the linked list has a bunch of elements in it but they are all empty strings. Any idea of what the problem can be?

Upvotes: 1

Views: 35

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

The problem is this declaration:

char copy[256];

copy is a local variable, so storing it for later use is not allowed.

Replace it with

char *copy = new char[256];

to get this problem fixed.

Upvotes: 1

Related Questions