结构中的指针问题

时间:2012-11-24 02:49:20

标签: c++ pointers struct

我遇到了返回指向结构的指针的问题。有人可以解释我做错了吗?我希望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);
    }
}

3 个答案:

答案 0 :(得分:3)

您需要打开编译器警告。

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

要解决此问题,请将其替换为:

            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 Found\n";
    }

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

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

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