我编写了一组函数,它们共同从 .csv 文件构建了一个“Hubs”列表。我希望在我的 main 函数中生成这些集线器的链接列表我有一个“头”指针,我可以将其传递给 main 中的其他函数。
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 在其范围内成功创建了 HubNode,但是当我尝试从 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
提供一个合适的构造函数,它将 sname
和 slocation
作为构造参数并初始化节点 next
成员为 NULL。如果你这样编码,添加就变得简单了:
void HubNode::AddHub(const string& sname, const string& slocation, HubNode **head)
{
while (*head)
head = &(*head)->next;
*head = new HubNode(sname, slocation);
}
关于C++:将链表传递给静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22904399/