【问题标题】:Segment fault pointers段故障指针
【发布时间】:2012-03-28 09:46:20
【问题描述】:

我试图实现一个链表数据类型的小样本。我创建了一个包含一个值的结构节点,一个跟踪所有节点的结构列表(以链表格式)。最后是一个类,它是两个结构的通用数据类型。

我运行程序时,总是一到步骤就报段错误错误: item->link[i++] = 新节点(输入)

代码:

struct Node
{
    int val;

    Node();
    Node(int x);
};

struct List
{
    Node *link[20];

    List();
};

class pol
{
    public:
        void read_txt(ifstream &file);

    private:
        List *item;
};

void pol::read_txt(ifstream &file)
{
    int input, i;
    i = 0;

    file >> input;

    cout << "Value read from the file: " << input << endl;

    while(input != 0)
    {
        item.link[i++] = new Node(input);
        file >> input;
        cout << "Value read from the file: " << input << endl;
    }
}

我想要做的是,创建一个新节点,其值为“输入”,我从读取文件中获得。接下来,我想创建一个连接所有节点的链表。

【问题讨论】:

  • item.link 不应编译为itemList*: item-&gt;link

标签: c++ memory pointers linked-list segmentation-fault


【解决方案1】:

成员item 从未初始化。据我所知,根本没有理由让它成为指针。就让它List item;

【讨论】:

  • 如果我这样做了,我将如何链接我正在创建的节点??
  • @John:就像您发布的代码一样...item.link[i++] = new Node(input);。 (那些节点需要删除顺便说一句。也许你应该考虑一个智能指针)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 1970-01-01
  • 1970-01-01
  • 2016-09-09
  • 2018-01-19
相关资源
最近更新 更多