开发者

linked list of type void*

I'm trying to read a text file and store each line in a node of a link list of type void*. Here's the header file of the list.

#ifndef LINKEDL
#define LINKEDL

struct node_s {
    void *data;
    struct node_s *next;    
};

struct node_s *node_create(void*);
struct node_s *list_insert_after(struct node_s*, void*);
struct node_s *list_insert_beginning(struct node_s*, void*);
int list_remove(struct node_s*, struct node_s*);
int list_foreach(struct node_s*, int(*)(void*));
int printstring(void *s);


#endif

All the linked list functions have been thoroughly tested, so I guess the problem is with how I use it. What I want to achieve is the have one line in each node and what I have now is last line in every node. I guess it has something to do with the char pointers but have already spent two hours on that without a spectacular breakthrough, so maybe someone could help? Also the list I use is a modified list as seen here.

 if (file == NULL)
 {
    perror("Error opening file");
 }
 else 
 {
     char mystring[SIZE];
     char temp[SIZE];

     list = node_create((void*)mystring);
     current = list;
     while (fgets(mystring, SIZE, file) != NULL)
        {
            strcpy(temp, 开发者_Python百科mystring); 
            printf("%d\t%s",counter++,temp);
            current=list_insert_after(current, (void*)temp);                    
            }
            fclose(file);

        }

UPDATE: Thank you All.


You are creating each node using a single array, temp. Every time you read a line, you replace the contents of temp with the last line you read. That's why you have the last line on every node (you are referring to the same memory location in every node).

What you should do, is to allocate memory dynamically for each line using malloc. Thus, you should pass the pointer to the newly allocated memory to list_insert_after instead of passing temp.


Remove the line:

strcpy(temp, mystring); 

And change the line:

current=list_insert_after(current, (void*)temp);

To

current=list_insert_after(current, strdup(mystring));


Think about this - you have a temporary char array on stack which is getting destroyed upon exiting out of the scope (of else block) and you are inserting pointer to that array into a list. So after all, the list will end up having pointers to destroyed/incorrect data. The behavior is undefined.

You have to allocate memory dynamically for each string (and not forget to clean it up). The strdup can be useful here. Just don't forget to call free when removing/dropping string from that list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜