我在理解指针方面遇到了很多麻烦,而且我已经到了需要一点指导的地步。这是我到目前为止编写的代码:
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
using namespace std;
//Declare structure
struct Airports{
string name;
string airID;
double elevation;
double runway;};
void dispdata(Airports *);
void getdata(Airports *);
int main()
{
Airports *airptr;
airptr = new Airports [3];
getdata(airptr);
dispdata(airptr);
system ("PAUSE");
return 0;
}
void getdata(Airports *p)
{
for (int i = 0; i < 3; i++)
{
cout << "Enter the name of airport " << i+1 << ": ";
getline(cin, p->name);
cout << "Enter the airport " << i+1 << " identifier: ";
getline(cin, p->airID);
cout << "Enter the elevation for airport " << i+1 << ": ";
cin >> p->elevation;
cout << "Enter the runway length for airport " << i+1 << ": ";
cin >> p->runway;
cout << endl;
p++;
}
cout << "Thanks for entering your values!";
}
void dispdata(Airports *p)
{
cout << "\nHere are the data values you entered:" << endl;
cout << "\n\t\tAirport info" << endl;
cout << "Airport\tAirID\tElevation\tRunway Length" << endl;
cout << "----------------------------------------------------------------" << endl;
cout << fixed << setprecision(2);
for (int i = 0; i<3; i++)
{
cout << p[i].name << "\t" << p[i].airID << "\t" << p[i].elevation << "\t" << p[i].runway << endl;
p++;
}
}
这个想法是创建一个动态分配的结构数组,并将一个可以指向数组每个元素的指针传递给两个函数。这可以成功编译,但是因为我不太了解它的语法,所以它不会很好地结束。
我敢肯定,主要问题在于 getdata 函数。每次我尝试将其更正为我认为应该的方式时,我都会遇到语法错误。如何正确更改数组每个元素中指针指向的值?