[英]Segmentation fault when assigning value in double pointer
我有一個雙指針,用於創建鏈接列表數組。 基本上,我試圖從數組中的“城市”中獲取數據,並在此雙指針的“行”部分中分配這些城市,以便可以使用單獨的“飛行”數據遍歷這些行。文件,如果它們匹配,則將所有數據鏈接到雙指針中的特定行上。
我的type.h文件,其中包含該節點的結構,等等:
#ifndef TYPE_H
#define TYPE_H
#include<string>
struct flight
{
int flightID;
std::string origin;
std::string destination;
int price;
};
typedef flight listItemType;
struct Node
{
listItemType data;
Node * next;
};
typedef Node ** nodePtr;
typedef Node * node;
#endif
我的flightMap.h文件包含我所有的類對象:
#include "type.h"
#include <string>
using namespace std;
const int MAX = 50;
#ifndef flightMap_Class
#define flightMap_Class
class flightMapClass
{
private:
int size;
string* cities;
nodePtr flights;
node Head;
public:
flightMapClass();
~flightMapClass();
void readCities();
void readFlights();
};
#endif
還有我的flightMap.cpp,其中包含這些對象的操作:
#include "flightMap.h"
#include <string>
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
flightMapClass::flightMapClass()
{
size = 0;
Head = NULL;
}
flightMapClass::~flightMapClass()
{
node cur = Head;
while(Head!=NULL)
{
cur->next = NULL;
delete cur;
Head = Head->next;
cur = Head;
}
}
void flightMapClass::readCities()
{
int index = 0;
ifstream fin;
fin.open("cities.dat");
fin >> size;
cities = new string[size];
while(fin.peek()!=EOF)
{
fin >> cities[index];
index ++;
}
for(int i = 0; i < index -1; i++)
{
cout << cities[i] << endl;
}
fin.close();
}
void flightMapClass::readFlights()
{
cout <<"Reading into Flight Data" << endl;
flights = new Node * [size];
for(int i = 0; i < size; i++)
{
flights[i]->data.origin = cities[i];
cout << flights[i]->data.origin << endl;
}
}
當我嘗試運行該程序時,輸出如下(在我的主文件中,我先運行readCities,然后運行readFlights,因此我確定這些城市確實可以正確加載到要加載的數組中。 “ readCities”,因為它們確實正確地完成了輸出):::
Albuquerque
Chicago
San-Diego
Nashville
San-Francisco
Miami
Dallas
Washington-DC
St-Louis
New-York-City
Los-Angeles
Boston
Las-Vegas
Orlando
Columbus
Seattle
Atlanta
Memphis
Houston
Austin
Denver
Minneapolis
Tampa
Portland
Kansas-City
Phoenix
Philadelphia
San-Jose
Charlotte
Detroit
reading flights
Reading into Flight data
Segmentation fault
...我基本上確定它來自這些代碼行:
flights[i]->data.origin = cities[i];
cout << flights[i]->data.origin << endl;
如何將數據分配到航班的“行”部分,以免出現分段錯誤? 這不是設置它的正確方法,因為從我的外觀來看,它是將字符串分配給字符串? 我很困惑。
flights = new Node * [size];
是不足夠的。 這只是Node指針的數組 。 指針尚未指向已分配的節點。
您還需要分配每個節點。
for(int i = 0; i < size; i++)
{
flights[i] = new Node;
^^^^^^^^^^^^^^^^^^^^^^^^^^
flights[i]->data.origin = cities[i];
cout << flights[i]->data.origin << endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.