2012-12-12 95 views
2

我试图动态分配一个结构,并且需要知道我是否正确地进行了操作。根据我的书,我是。但是我的编译器给我一个错误。下面是相关代码:“没有存储类或类型说明符”为结构动态分配内存

#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定义为指向该结构的指针。我在这里错过了什么吗?

预先感谢任何回信

+0

考虑使用'std :: vector'。这个错误更像是表示'airptr.name'。 – chris

+0

我想,但对于我的任务,我必须使用一个数组>><< –

+0

这里所有的东西都用mingw 4.6编译得很好。你能发布编译器输出的所有错误吗?可能还有其他事情发生在 –

回答

2

正如我写这篇文章,在这个问题所提出的代码是&hellip;

#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,你会避免很多错误和痛苦的工作。