cip
cip

Reputation: 79

linked list change when i change the array of character

The problem is when the second time i put a any word the q->ch in the if statement change to the new word .. I want q become the pointer of the start of the linked list

while(true){
    tmp=(list*)malloc(sizeof(list));
    printf("\n put any word:");
    scanf("%s",name);
    printf("\n");
    tmp->ch=name;
        if (i==0)
    {
        q=p=tmp;

    }
    else
    {
        p->nxt=tmp;
        p=tmp;
    }

    printf("when you want to end press y \n");
    scanf(" %c",&c);
    if (c=='Y' || c=='y')
    {
        break;
    }
    i++;
}   

Upvotes: 0

Views: 40

Answers (1)

Diego
Diego

Reputation: 1819

q does point to the first node in the list. The problem is that when you do

tmp->ch = name

you are only copying an address. So, every node gets to point to the same bufer which will end with the last word.

To fix it, a copy of the string needs to be done:

tmp->ch = strdup (name)

Upvotes: 2

Related Questions