gpt4 book ai didi

c - C中的字符串链表

转载 作者:太空宇宙 更新时间:2023-11-04 08:14:51 25 4
gpt4 key购买 nike

我试图在 C 中创建一个字符串链表,但在将第一个节点添加到列表中时遇到了问题。无论出于何种原因,即使我将 head 变量引用到 newNode,我的程序也会打印 NULL,但它不会将字符串从结构指针复制到结构指针。任何帮助表示赞赏。谢谢!

#include "stdafx.h"
#include <stdlib.h>
#include <string.h>

typedef struct stringData {
char *s;
struct stringData *next;
} Node;

Node *createNode(char *s) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->s = s;
newNode->next = NULL;
return newNode;
}


void insert(Node *head, Node *newNode) {
if (head == NULL) {
head->s = newNode->s;
head = newNode;
}
}

void printList(Node *head) {
while (head != NULL) {
printf("%s\n", head->s);
head = head->next;
}
}



int main()
{
Node *head = createNode(NULL);

Node *a = createNode("A");
insert(head, a);

printList(head);
return 0;
}

最佳答案

以下代码片段是错误的:

void insert(Node *head, Node *newNode) {...}
...
insert(head, a);

您需要通过引用传递指针。当前您正在更改本地副本(参数)。

修复
将您的 insert 更改为:

void insert(Node **head, Node *newNode) {...}

并调用为:

insert(&head, a);

还有什么
至少插入(可能还有)更多函数不是万无一失的(保证空指针解引用,else案件未处理等)。您需要调试和修复许多此类情况。在编码之前在纸上正确地运用您的方法可能会有所帮助。

关于c - C中的字符串链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36394860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com