结构中的指针问题

Pointer Issues within a struct

本文关键字:问题 指针 结构      更新时间:2023-10-16

我在返回指向结构的指针时遇到问题。有人可以解释我做错了什么吗?我希望search()返回指向匹配输入的指针。这将存储在一个向量中,以防"数组"中有重复项。这似乎有效,但是我无法从返回的指针中获取"数据"?

struct Node
{
    int data;
    Node *left;
    Node *next;
};
vector<Node *> array;

void find(int & input)
{
     currentSize = 0;
     vector<Node *> hold;
    for( int i = 0; i < array.size( ); i++ ){
        if(search(array[i], input) != NULL)
        {
            hold.push_back(search(array[i], input));
        }
        else{
            cout << "The Key is not found" << endl;
        }
    }
    for(int i = 0; i < hold.size(); i++)
    {
        cout << hold[i] << endl;
        //Problem here:: I want to see the "data" that the search function returned not the hex value
    }
}

Node * search(Node * x, const int & input)
{
    if( x == NULL )
    {
       return NULL;
    }
    else
    {
        if(input == x->element)
        {
            return x;
        }
            search(x->left, input);
            search(x->next, input);
    }
}

您需要打开编译器警告。

并非所有搜索代码路径都返回一个值,特别是,如果您的编译器没有脑死亡,您应该收到警告。

要解决此问题,请替换以下内容:

            search(x->left, input);
            search(x->next, input);
    }
}

跟:

            Node* leftSearch = search(x->left, input);
            if (leftSearch)
              return leftSearch;
            return search(x->next, input);
    }
}

search()递归调用不会自动将其返回值传递到当前函数的返回值。 :)

此外,正如 Zack 所指出的,您需要查看Node的某些子字段才能打印它。 首先检查返回值是否nullptr(或在不支持 C++11 的编译器中NULL)(如果为 null,则无法安全地取消引用它,并且指示搜索失败)。

如果未nullptr ',请在打印前对其进行->data

即,更改:

    cout << hold[i] << endl;

自:

    if (hold[i]) {
      cout << "Found: " << hold[i]->data << "n";
    } else {
      cout << "Not Foundn";
    }

请注意,我没有使用 std::endl ,因为我看不到需要刷新每行上的缓冲区。

您正在打印 hold[i] ,这是指向节点的指针,而不是 hold[i]->data ,这是您想要打印的内容。

此外,这段代码几乎肯定会像筛子一样泄漏和/或损坏堆,但你还没有显示足够的代码让我告诉你那里出了什么问题。

        search(x->left, input);
        search(x->next, input);

这两个调用的结果只是被忽略。您可能应该存储第一次搜索的结果,如果不NULL,则返回它,否则返回第二次搜索的结果

Node* res = search(x->left, input);
if (res) return res;
return search(x->next, input);