我正在读取文件并尝试将其添加到链表中,然后遍历链表以打印出内容。我有点麻烦,因为我的输出不是打印整个链表,而是多次打印最后一个元素。我已经在下面发布了代码并且我只发布了片段,并且为了简洁删除了错误检查。
typedef struct Node{
char* data;
struct Node* next;
} NODE;
NODE* head = NULL;
NODE* tail = NULL;
int main(int argc, char* argv[])
{
char buffer[1024];
FILE* fp = fopen(argv[1], "r");
while(fscanf(fp, "%1023s", buffer) == 1)
{
addNode(buffer);
}
print_linked_list(head);
return 0;
}
void print_linked_list(NODE* head)
{
NODE* ptr = head;
while(ptr != NULL)
{
printf("%s ", ptr -> data);
ptr = ptr -> next;
}
}
void addNode(char* str)
{
NODE* newNode = createNode(str);
if(head == tail && tail == NULL)
{
head = newNode;
tail = newNode;
head -> next = NULL;
tail -> next = NULL;
}
else
{
tail -> next = newNode;
tail = newNode;
tail -> next = NULL;
}
}
NODE* createNode(char* str)
{
NODE* newNode = malloc(sizeof(NODE));
newNode -> data = malloc((1 + strlen(str)) * sizeof(char));
newNode -> data = str;
newNode -> next = NULL;
return newNode;
}
因此,如果一个文件包含一些文本,如“你好吗”,我希望我的输出打印为“你好吗”,但我得到的只是“你你你”。我该如何解决这个问题?
最佳答案
在
newNode -> data = malloc((1 + strlen(str)) * sizeof(char));
newNode -> data = str;
您是否想从 str
复制字符串 (strncpy()
) 到 newNode->data
?
使用 newNode->data = str;
指针被复制,内容(例如“你好吗”)不被复制。
一个简单的方法可能是
newNode->data = strdup(str);
来自 http://man7.org/linux/man-pages/man3/strdupa.3.html
The strdup() function returns a pointer to a new string which is a duplicate of the string s. Memory for the new string is obtained with malloc(3), and can be freed with free(3).
关于C 打印链表不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40269681/