结构中的指针问题
Pointer Issues within a 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);
}
}
您需要打开编译器警告。
并非所有搜索代码路径都返回一个值,特别是,如果您的编译器没有脑死亡,您应该收到警告。
要解决此问题,请替换以下内容:
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);
相关文章:
- 关于 c++ 函数中指针赋值的简单问题
- 链表指针问题
- C++ 关于指针取消引用的技术问题
- C++中的指针和常量问题不大
- 包含矢量指针的结构的内存释放问题
- 指针问题:从不兼容的类型"int"分配给"int *"
- 将字节数组转换为带有字节序问题的指针
- 关于如何使用指向主窗口的指针的 QT 问题
- 当成员值从指针更改为非指针时,C++常量问题
- 为什么循环会导致指针出现问题?
- 使用指针计算堆栈问题的大 O 表示法
- 构造函数 (C++) 中的 char 指针参数存在问题
- 指向包含对齐 C 结构C++类的 C 指针的对齐问题
- 涉及指针和手动实现的矩阵类的问题
- 从基指针到派生的强制转换问题
- 迭代器的指针操作问题
- 64 位迁移问题:指针更改
- C++模板使用问题指针
- 跳到C++第13章练习问题4-指针
- 用std::pair数组初始化std::map问题(指针错误?)