我正在尝试动态分配结构,并且需要知道我做得是否正确。根据我的书,我是。但我的编译器给了我一个错误。相关代码如下:
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
using namespace std;
//Declare structure
struct Airports{
string name;
string airID;
double elevation;
double runway;};
Airports *airptr;
airptr = new Airports[3];//This is where the error is happening
编译器似乎认为airptr“没有存储类或类型说明符”。我不明白当我定义一个结构,然后将airptr 定义为指向该结构的指针时,这是怎么看的。我在这里遗漏了什么吗?
提前感谢您的回复
最佳答案
当我写这篇文章时,问题中提供的代码是......
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
using namespace std;
//Declare structure
struct Airports{
string name;
string airID;
double elevation;
double runway;};
Airports *airptr;
airptr = new Airports[3];//This is where the error is happening
对于函数外部的非声明语句,编译器会尝试将其解释为声明,但会失败。
将其放入 main
函数中。
此外,通过使用 std::vector
而不是原始数组、指针和 new
,您可以避免大量错误和痛苦的工作。
关于c++ - 为结构体动态分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13831840/