【问题标题】:Storing strings dynamically in a linked list在链表中动态存储字符串
【发布时间】:2015-01-12 09:00:21
【问题描述】:

我想在 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 *â

我在这一点上很困,我不确定如何成功地实现它;有什么建议吗?

【问题讨论】:

  • if (list == NULL){ --> while(freeSpot->next != NULL){
  • 对于scanf,您不需要额外的s,这很好scanf("%s", string); %s 在读取空格字符后停止读取。另请注意,由于您没有为字符串输入分配新内存,因此列表中的所有字符串都将包含相同的值
  • void addToLinkedList(node* list, char str[]) { --> void addToLinkedList(node** list, char str[]) {
  • if(*list == NULL) { *list = newNode;}

标签: c string dynamic linked-list arrays


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    删除:

    newNode->word = str;
    

    并添加:

    strcpy(nweNode->word, str);
    

    你是复制到当前节点的成员词,而不是复制到下一个节点。

    在复制之前,您应该检查str 的长度是否不超过 (50-1)。

    【讨论】:

    • 哇,谢谢,真不敢相信我没有发现这么愚蠢的错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 2022-01-21
    • 2021-06-30
    • 1970-01-01
    相关资源
    最近更新 更多