Can deque store char* in C?

136 views Asked by At

I need a deque of strings read from a txt file. They are read successfully (I checked it by printing them out in while.

    while ((read = getdelim(&word, &len, ' ', fp)) != -1) 
{
    printf("!%s\n", word); 
    strcpy(s, word);
    printf(" read string is : %s\n", s);
    deque_push_back(d,s);
}

The code works. The only thing is that when I'm trying to print the deque, all the values are "aaa", but here's the actual contents of my file: hhh aaa hfhf hhh nnn bbbb aaa bbb aaa

I tryed out to push values this way:

int i;
for (i = 0; i < 10; i++)
{ 
    char * s = "ssss";
    deque_push_back(d,s);
}
s = "llll";
deque_push_back(d,s);

This code works totally fine and all the values in my deque are correct.

I have no idea what's the problem and will be really thankfull if someone can help me.

1

There are 1 answers

0
Armali On

You are storing always the same pointer in your deque; you're just changing what's in the memory to which it points. You need to not just strcpy(), but create a new object to copy the data into. If you have strdup() then that should help. Otherwise, for each string, malloc()sufficient memory to strcpy() into, and enqueue the pointer to that space. – John Bollinger