0

這是我第一次提出問題。這個論壇對我有很大的幫助,所以我會嘗試只給你很多部分:如何調用預定義類型的函數struct

我有兩個功能,一個是搜索功能,通過指針搜索預先創建的二叉搜索樹(我可以顯示搜索樹通過一個不同的功能,所以我知道它是填充)爲一個特定的值。它將來自該節點的信息放入具有相同類型的變量(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:如何創建一個返回數據結構的函數?

+0

函數不是'struct'。函數**返回** a **值**,它有一個類型。此外,溝任何書教'void main' - 這絕對是'int main'。 – MSalters

+0

你可以通過讓'node'包含一個'Nubline'來代替同名的略有不同的3個成員來簡化你的代碼 –

回答

0

好吧,這裏是我的解決方案:

我作廢的功能,使用全局變量Nubline r;,並設置t到如下:

void SearchbyID(node* &t, int x) 
{ 
    if (t != NULL); 
    { 
     if (t->id == x) 
     { 
      r.ID = t->id; 
      r.Name = t->name; 
      r.Amnt = t->balance; 
     } 
//I also changed this to make it more efficient and not throw an access violation up by the if(t->id == x) statement 
     if (x < t->id) 
     { 
      SearchbyID(t->left, x); 
     } 
     if (x > t->id) 
     { 
      SearchbyID(t->right, x); 
     } 
    } 
} 
//PART B 
//Option 1: show Balance when ID is given 
void BalancebyID() 
{ 
    int num; 
    cout << "\tWhat is your ID number? "; cin >> num; 
    SearchbyID(rootID, num); 
    cout << "\t\t"<< r.Name << " your balance is $" << r.Amnt; 
} 

這是對我工作。謝謝大家的解決方案;它幫助我隔離問題並找到解決方案。

1

爲確保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 
} 
+0

或者更好的是,返回'nullptr'的值。 – kfsone

+0

@kfsone你是對的。 – Wentao

+0

使用智能指針而不是原始擁有指針。 – Jarod42

相關問題