[英]C++: Passing a linked list to a static function
我編寫了一組函數,這些函數共同從.csv文件構建“集線器”列表。 我希望在主函數中生成這些集線器的鏈接列表,我有一個“頭”指針,可以將其傳遞給main中的其他函數。
主要代碼:
HubNode *hh = NULL;
HubNode **head;
*head = hh;
Tools::loadHubs(head);
cout << hh->name; /* HubNodes have a string called "name" */
工具中的代碼:
void Tools::loadHubs(HubNode **head)
{
string line, name, location;
// headFlights = currFlights = prevFlights = NULL;
ifstream myfile("Hub.csv");
if (myfile.is_open())
{
while (getline(myfile, line)) {// Omit the Caption Line.
while (getline(myfile, name, ','))//Get every value in order.
{
getline(myfile, location, '\n');
// cout << line << "\n";
// cout << name << "\n";
// cout << location << "\n";
HubNode::AddHub(name, location, head);
}
}
myfile.close();
}
else { cout << "\nUnable to open file\n"; }
}
HubNode中的代碼:
void HubNode::AddHub(string sname, string slocation, HubNode **head)
{
HubNode* newNode = new HubNode;
HubNode *point;
newNode->next = NULL;
newNode->name = sname;
newNode->location = slocation;
if (*head != NULL)
{
HubNode *curr = *head;
while (curr->next != NULL)
{
curr = curr->next;
}
curr->next = newNode;
}
else
{
point = newNode;
*head = point;
}
}
我認為以這種方式使用指向列表頭的雙指針將是可行的,因此從main中的“ hh”開始,我將可以訪問整個鏈接列表。
當我編譯並開始調試時,我可以看到AddHubs在其范圍內成功創建了HubNodes,但是當我嘗試從main訪問任何元素(例如,通過cout << hh-> name)時,出現了分段錯誤。
我做錯了什么? (讓我知道是否需要發布更多代碼...)
您不會這樣做:
int value = 10;
int *p;
*p = value;
那么,您為什么認為這會起作用:
HubNode *hh = NULL;
HubNode **head;
*head = hh;
間接尋址是相同的,只是類型已更改。 並且這兩個片段都調用未定義的行為 。 此代碼應執行以下操作:
HubNode *hh = NULL;
Tools::loadHubs(&hh);
cout << hh->name;
此外,您的添加函數應為:
void HubNode::AddHub(const string& sname, const string& slocation, HubNode **head)
{
HubNode* newNode = new HubNode;
newNode->next = NULL;
newNode->name = sname;
newNode->location = slocation;
while (*head)
head = &(*head)->next;
*head = newNode;
}
如果為HubNode
提供一個適當的構造HubNode
,它將sname
和slocation
作為構造參數,並將節點的next
成員初始化為NULL, slocation
變得更加簡單。 如果您編寫該代碼,則添加內容將變得簡單:
void HubNode::AddHub(const string& sname, const string& slocation, HubNode **head)
{
while (*head)
head = &(*head)->next;
*head = new HubNode(sname, slocation);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.