编译器会给我分段错误。
我有一个结构Car
,它包含关于汽车的信息
struct Car {
string name;
string color;
int serialNumber;
int regestrationNumber;
int yearMade;
int yearInspection;
int price;
};
我有一个链接列表
struct Node {
Car obj;
struct Node* next;
};
我这样声明:
struct Node* head = NULL;
我用这个代码块收集信息
cout << "name: " ;
getline(cin, newCar[size].name);
cout << "color: ";
getline(cin, newCar[size].color);
cout << "serial number: ";
cin >> newCar[size].serialNumber;
cout << "regestration number: ";
cin >> newCar[size].regestrationNumber;
cout << "year made: ";
cin >> newCar[size].yearMade;
cout << "inspection year: ";
cin >> newCar[size].yearInspection;
cout << "price: ";
cin >> newCar[size].price;
cin.get();
我将所有这些信息添加到结构中,并使用函数将该结构推送到链表中
void push(struct Node** head, Car node_obj)
{
Node* newNode = newNode;
newNode->obj = node_obj;
newNode->next = (*head);
(*head) = newNode;
}
现在有趣的部分是:我使用函数void output(Car strk, int first)
打印这样的结构的内容(output()
基本上是三个printf()
函数(
while (headCopy != NULL) {
output(headCopy->obj, first);
headCopy = headCopy->next;
first = 1;
}
现在,当链表中有两个以上的元素时,它会显示除第一个元素外的所有元素,其中显示segmentation fault
。我认为问题是,到最后headCopy = headCopy->next;
根本没有指向任何东西,但话说回来,当它有1或2个元素时,为什么它不给我那个错误。
因为@mike-vine说线有问题
Node* newNode = newNode;
我应该在哪里输入
Node* newNode = new Node;
非常愚蠢的错误。