gpt4 book ai didi

C++ 程序在读取 NULL 引用时崩溃

转载 作者:行者123 更新时间:2023-11-30 01:13:42 25 4
gpt4 key购买 nike

这是 C++ 中的链接结构。这里的所有变量和对象都应该有定义的地址。但是,执行情况并非如此。

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
struct LineData {
int ID;
char name[33];
LineData *next;
};

class Line {
private:
LineData *pointerHead;
LineData *pointerToTail;
int numObjects;
public:

Line();
~Line();

void enterLine(int ID, char *data);
void enterLine(LineData *lindat);
LineData *exitLine();
int count();
};

Line::Line() {
pointerHead = NULL;
pointerToTail = NULL;
numObjects = 0;
/*pointerHead = NULL;
pointerToTail = NULL;*/
}

/** Puts an item into the line. **/
void Line::enterLine(int ID, char *data) {

LineData *temp;
cout << "Inner sanctums called.\n";
temp = new LineData;
temp->ID = ID;
strcpy(temp->name, data);
temp->next = NULL;
cout << "Temp created.\n\n";
//cout << "pointerHead is... ... " << pointerHead << "!\n"; Not going to work!
/* Insert into the Line */
if(pointerHead != 0) { /* Insert as first in this Line/You shall not pass! Program will not let you pass! BOOM! Crash! */
cout << "If tried.\n";
pointerToTail->next = temp;
pointerToTail = temp;
}
else /* Insert at Tail of the Line */
{
cout << "pointerHead == NULL. What are you going to do about it?\n";
cout << temp->ID << "\n";
pointerHead = temp;
pointerToTail = temp;
cout << "Inserted into Line!\n";
}
}

/** ......
......
..........
..........
...... **/

正确编译。

int main() {
Line *GeorgiaCyclone;
Line *GiletteIce; // Shaved Ice.
Line *WoodenMagic;
Line *SteelCityNinja;
Line *Egbe; // Hawk.

GeorgiaCyclone->enterLine(4, "Preston");
Egbe->enterLine(2, "Felix");


return 181;
}

每行的地址在创建时都设置为 NULL。使用 this 没有区别。这怎么可能发生?如何缓解这种崩溃?

最佳答案

Line *GeorgiaCyclone;

这会创建一个指向 Line 的指针,但不会创建一个 Line 供其指向。您需要为其分配 Line 的地址:

Line *GeorgiaCyclone = new Line

更好的是,您可以完全避免在 main() 中使用指针:

Line GeorgiaCyclone;

您在 main() 中声明的所有其他 Line* 也是如此。

关于C++ 程序在读取 NULL 引用时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31630199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com