Dustin Burns
Dustin Burns

Reputation: 307

Dynamically allocating memory for structures

I'm trying to dynamically allocate a structure, and need to know if I'm doing it right. According to my book, I am. But my compiler is giving me an error. Here is the relevant code:

#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

The compiler seems to think that airptr "has no storage class or type specifier." I don't get how that can be seeing as I defined a structure and then defined airptr as a pointer to that structure. Am I missing something here?

Thanks in advance for any replys

Upvotes: 2

Views: 183

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145239

As I'm writing this, the presented code in the question is …

#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

With a non-declaration statement outside a function the compiler tries to interpret it as a declaration, but fails.

Put that in a main function.


Also, by using std::vector instead of raw arrays, pointers and new, you would avoid a lot of errors and painful work.

Upvotes: 2

Related Questions