为结构动态分配内存

Dynamically allocating memory for structures

本文关键字:内存 动态分配 结构      更新时间:2023-10-16

>我正在尝试动态分配一个结构,并且需要知道我是否做得对。 根据我的书,我是。 但是我的编译器给了我一个错误。 以下是相关代码:

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