【问题标题】:Getting contains function of linked list to work properly in C获取包含链表的功能以在 C 中正常工作
【发布时间】:2014-02-03 18:58:01
【问题描述】:

我用包含函数实现了一个链表。它像这样使用 strcmp:

    void contains(NODE *head, char data)
{
    NODE *this = head;
    while(this != NULL && strcmp(this->data, data) != 0)
    {
        if(strcmp(this->data, data) == 0){
            printf("Found data %s\n", this->data);
        }
        this = this->next;
    }
}

在 main 我有(我在最后一行使用包含):

NODE *head;
head = malloc(sizeof(NODE));

bool headNode = true;
char userID[1000];
char test[180] = "monkey"; // for testing contains function
while((fgets(userID,1000,stdin) != NULL)){
    if(headNode == true)
    {
        head = insert(NULL, userID);
        headNode = false;
    }
    else
    {
        head = insert(head, userID);
    }
}
contains(head, test);

我还在学习C,指针还是有点混乱。我有一种感觉,我犯了一个基本的错误。我想让用户自己输入一些字符串并检查列表是否包含该字符串,但我什至无法让 contains 使用此测试字符串。我知道我正在比较的测试字符串确实在列表中,我有一个我用来验证的 printList 函数。

【问题讨论】:

  • strcmp(this->data, data) != 0strcmp(this->data, data) == 0 不一致。

标签: c debugging pointers linked-list strcmp


【解决方案1】:

test 是一个指向你在函数contains(head, test); 中传递的数组的指针,所以调用函数中的正式参数应该是一个指针,contains(NODE *head, char * data) { ...

【讨论】:

    【解决方案2】:

    将指针“test”传入函数“contains()”:

    应该是:

    void contains(NODE *head, char * data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-27
      • 2021-06-15
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 2021-12-03
      • 2019-12-29
      • 1970-01-01
      相关资源
      最近更新 更多