将链表转换为指针数组时出错

Error when converting a linked list into an array of pointers

本文关键字:数组 出错 指针 链表 转换      更新时间:2023-10-16

这是程序提示符:

编写一个C++程序来处理文件中的元素周期表信息。每个元素都有一个原子序数、一个名称、一个缩写和一个质量。您的计划必须包括:

  1. 要在头文件中定义的元素结构:Element.h
  2. 一个函数read_table,它将返回从文件中读取的元素数,并通过引用参数返回指向读取元素的指针数组的指针。数据文件位于/user/tvnguyen7/data/periodictable.dat。此函数必须通过构造链表来读取数据,并将链表转换为指针数组。此函数的原型将包含在 Element.h 文件中。该函数在任何错误条件下都将返回 0。
  3. 一个主程序,它将调用read_table读取表,使用元素名称对表进行排序,并使用所需的输出格式打印出表。你可以在 cstdlib 中使用 qsort,也可以编写自己的排序函数。
  4. 必须正确分配和取消分配动态内存。

这是我对periodic_table.cpp:

#include <iostream>
#include <cstdlib>
#include "Element.h"
#include <string>
#include <iomanip>
using namespace std;
int main() {
int count = 0;
Element **pt = new Element *[count];
cout << setw(30) << left << " Periodic Table by K. Nguyen" << endl;
cout << endl;
cout << setw(30) << " Number of elements: " << endl;
cout << endl;
cout << setw(5) << " Name" << right << setw(20) << "Abr" << setw(5) << " ANo" << setw(8) << "Mass" << endl;
cout << setw(20) << left << " --------------------" << setw(4) << right << "---" << setw(5) << "----" << setw(8) << "-------" << endl;
read_table(&count, pt);  
delete [] pt;
return 0;
}

以下是我对read_table.cpp

#include <fstream>
#include <iostream>
#include <string>
#include "Element.h"
using namespace std;
int read_table(int *count, Element **ppt){
struct Node {
Element *pElement;
Node *next;
};
int temp = 0;
int aNum;
string aBr;
double mass;
string name;
Node *n = nullptr;
Node *h = nullptr;
Node *t = nullptr;
ifstream infile;
infile.open("periodictable.dat");
while(infile >> aNum >> aBr >> mass >> name){
Element *e = new Element;
e->ANo = aNum;
e->Abr = aBr;
e->Mass = mass;
e->Name = name;
n = new Node;
n->pElement = e;
n->next = nullptr;
if(h == nullptr){
h = t = n;
}
else {
t->next = n;
t = n;
}
temp++;
}
infile.close();
int i = 0;
for(Node *x = h; x, i < temp; x = x->next, i++){
ppt[i] = x->pElement;
}
*count = temp;
return 0;
}

以下是我对Element.h的内容:

#ifndef ELEMENT_H
#define ELEMENT_H
using namespace std;
struct Element {
int ANo;
string Abr;
double Mass;
string Name;
};
int read_table(int *count, Element **ppt);
#endif

我认为问题出在 for 循环中read_table.cpp:

int i = 0;
for(Node *x = h; x, i < temp; x = x->next, i++){
ppt[i] = x->pElement;
}

而且我不确定我是否正确传入了指针数组(这是在 periodic_table.cpp(:

int count = 0;
Element **pt = new Element *[count];
....
read_table(&count, pt);

错误是: 在函数 'main' 中: periodic_table.cpp: 未定义对 'read_table(int*, Element**(' 的引用

当我包含for循环时,我的程序无法运行;但是,没有它运行良好,所以我认为我在那里做错了什么,但我不知道是什么。请帮忙。

如果你使用的是Microsoft Visual Studio(我C++使用最多的一个(;转到解决方案资源管理器;复制read_table.cpp的路径;右键单击资源管理器中的"源文件"文件夹,添加现有项。然后将路径粘贴到其上。单击"确定",然后再次运行程序。它应该有效。