gpt4 book ai didi

c++ - 如何调用预定义结构类型的函数

转载 作者:行者123 更新时间:2023-11-28 05:41:29 25 4
gpt4 key购买 nike

这是我第一次提问。这些论坛对我非常有帮助,所以我会尽量只给你一些有趣的部分:

我有两个函数,一个是搜索函数,它通过指针搜索预先创建的二叉搜索树(我可以通过不同的函数显示搜索树,所以我知道它已填充)以获取特定值。它将来自该节点的信息放入具有相同类型变量(int、float 和 string)的预定义数据结构 Nubline,然后返回该数据结构。

这是我的代码:

struct node
{
int id;
string name;
float balance;
node *left;
node *right;
};
node *rootID, *rootName;

struct Nubline
{
int ID;
string Name;
float Amnt;
};
//Search function; the node is a pointer to a linked list with move id's node *left and node *right;
Nubline SearchbyID(node* &t, int x)
{
if (t != NULL)
{
if (t->id == x)
{
Nubline r;
r.ID = t->id;
r.Name = t->name;
r.Amnt = t->balance;
return r;
}
SearchbyID(t->left, x);
SearchbyID(t->right, x);
}
}
//function that calls the search function
void BalancebyID()
{
int num;
cout << "\tWhat is your ID number? "; cin >> num;
Nubline duke = SearchbyID(rootID, num);
cout << "\t\t"<< duke.Name << " your balance is $" << duke.Amnt;
}

void main()
{
//calling statement
BalancebyID();
system("pause");//pausing to view result
}

它抛出以下错误:

Expression: "(_Ptr_user & (_BIG_ALLOCATION_ALIGNMENT -1)) == 0

我想我已经将问题缩小到函数初始化,因为我可以使函数无效并运行(当然没有所有其他代码)。我还可以取消该函数,设置一个 Nubline 类型的任意全局变量并将其放在变量“r”所在的位置,然后在我的 BalancebyID 函数中使用它,但它只显示零,所以我可以假设它没有填充。

抱歉这篇冗长的帖子。

Tl;dr:如何创建返回数据结构的函数?

最佳答案

为确保 SearchbyID 正常工作,您应该将 return 添加到所有条件。

此外,您可以将返回类型设置为 Nubline* 然后您可以返回一个 nullptr 以指示未找到任何内容。

Nubline* SearchbyID(node* t, int x)
{
if(t == nullptr) return nullptr;

//else
if (t->id == x)
{
auto r = new Nubline();
r->ID = t->id;
r->Name = t->name;
r->Amnt = t->balance;
return r;
}

auto pLeft = SearchbyID(t->left, x);
if (pLeft) return pLeft;

return SearchbyID(t->right, x);
//return NULL if nothing found
}

关于c++ - 如何调用预定义结构类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36996278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com