【问题标题】:When inserting strings into linked list, newline occurs, and when fixed causes anomalous behavior?将字符串插入链表时,会出现换行符,固定时会导致异常行为吗?
【发布时间】:2021-07-22 05:22:53
【问题描述】:

我对 C 中的链表相当陌生,我很确定我走在正确的轨道上,但我一直坚持这一点,因为我不知道是什么导致了这个输出。这会导致问题,因为由于字符串格式的奇怪行为,我在搜索节点时无法匹配字符串。

我尝试过node->title[strcspn(node->title, "\n")] = 0;,但是当我在插入方法中使用它时,它并没有做我想做的事情。例如,我们有 Title: [HARDWARE\n] 并调用 (strcspn) 它会导致

[Title: [HARDWARE 而不是Title: [HARDWARE]

附:我只是使用方括号来解释字符串中多余的无关字符,因此我可以使用 strcmp() 比较它们。

有谁知道如何解决这个问题?

Enter title:
HARDWARE
TITLE to search for: [HARDWARE]
Current: []
]urrent: [ELECTRONICS
]urrent: [OUTSIDE GARDEN
]urrent: [INDOOR GARDEN
]urrent: [MILLWORK
]urrent: [LUMBER
]urrent: [APPLIANCES
]urrent: [HARDWARE
...

这是在使用上述任一行后打印 curr->title 时的输出。 我唯一做的另一件事是在我的主目录中列出打印列表下方的菜单以提供其他功能,但这是与填充链接列表中的节点相关的逻辑。

【问题讨论】:

  • strcspn 中尝试"\r\n" 而不是"\n"

标签: c struct linked-list singly-linked-list c-strings


【解决方案1】:

您的代码无效。

例如,函数insertSortedList(作为函数search)会产生多个内存泄漏,而且具有未定义的行为。

这些内存分配

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

没有意义。分配的内存没有使用,会丢失。

节点head一般可以等于NULL。因此,例如访问空指针的数据成员 next 会调用未定义的行为。

除此之外,指向头节点的指针在函数内没有改变,因为它是通过引用传递给函数的。

我将展示如何编写函数。尝试自己更新其他函数。

int insertSortedList( node **head, 
                           const char *title, 
                           const char *category, 
                           double time) 
{
    node *node = malloc( sizeof( node ) );
    int success = node != NULL;

    if ( success )
    {
        strcpy( node->title, title );
        node->title[ strcspn( node->title, "\n" ) ] = '\0';

        strcpy( node->category, category );
        node->category[ strcspn( node->category, "\n" ) ] = '\0';

        node->time = time;

        while ( *head != NULL && !( strcmp( node->title, ( *head )->title ) < 0 ) ) 
        {
            head = &( *head )->next;
        }

        node->next = *head;
        *head = node;
    }

    return success;
}

而且函数至少可以像这样调用

insertSortedList(&head, title, category, time);
                 ^^^^^

如果您使用的系统会附加从文件中读取的带有两个符号 '\r''\n' 的字符串,那么您可以使用以下 strcspn 调用

node->title[ strcspn( node->title, "\r\n" ) ] = '\0';

【讨论】:

  • @Patrick 您需要在 while 循环中再添加一个条件。
  • @Patrick 您应该按顺序或在指定位置插入新节点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
  • 2017-05-22
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 2021-10-06
相关资源
最近更新 更多