gpt4 book ai didi

c - 在链表中动态存储字符串

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:07 24 4
gpt4 key购买 nike

我想在 C 中创建一个链接列表,用户可以在其中输入将作为节点存储在列表中的字符串。这是我的节点结构:

typdef struct NODE {
char word[50];
struct NODE* next;
} node;

在我的主要方法中,我想提示用户输入一个字符串,然后调用一个将该字符串添加到链表的方法(但不包括空格后面的任何字符),并重复执行此操作直到用户输入一个终止进程的特定字符串,所以在我的主要方法中我有:

void main(){
node* fullList = NULL;
char stopString[5];
sprintf(stopString, "stop");
char string[50];
printf("Enter a word: ");
scanf("%[^ ]s", string);
while (strcmp(string, stopString) != 0) {
addToLinkedList(fullList, string);
printf("Enter a word: ");
scanf("%[^ ]s", string);
}
}

这是我的加法:

void addToLinkedList(node* list, char str[]) {
node* freeSpot;
node* newNode;

freeSpot = list;
if (list == NULL){
freeSpot = freeSpot->next;
}

newNode = (node *)malloc(sizeof(node));

newNode->word = str;
//strcpy(nweNode->next, str);
newNode->next = NULL;
freeSpot->next = newNode;

但是我得到一个错误:

"incompatible types when assigning to type âchar[256]â from type âchar *â"

如果我替换“newNode->word = str;”在下面注释掉这段代码后,我得到:

warning: passing argument 1 of âstrcpyâ from incompatible pointer type [enabled by default]
/usr/include/string.h:128:14: note: expected âchar * __restrict__â but argument is of type
âstruct NODE *â

我现在很困惑,我不确定如何成功实现;有什么建议吗?

最佳答案

此错误与注释行有关。注释掉后你保存文件了吗?你清理过项目吗?无论如何,这一行:newNode->word = str; 也会引起麻烦。请改用 strcpy。你想复制字符串,而不是指针。

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

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