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

标签 c string dynamic linked-list arrays

我想在 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/

相关文章:

c - 使用指针在 C 中复制字符串不显示预期结果

c# - 如何从动态类型泛型列表中获取属性信息?

c# - WCF 中的动态 ExpandoObject

c# - System.Convert.ToSingle() 问题,(1.5) 与 (1,5)

c - 在64位机器上处理文件但在32位机器上开发

java - 指向java中等效指针的指针

c - 读取文本文件

C++ 模板 : Create a specialized function for a specific data type

javascript - 在js中使用事件构造函数的一个很好的例子是什么?

c++ - 禁用编译