c++ - 为结构体动态分配内存

标签 c++ memory structure

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

#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/

相关文章:

Web应用程序的Mysql数据库结构

c++ - 具有不同参数的函数指针

c++ - 用户定义类的 Bind2nd 问题

c++ - 宏定义中预处理器标记周围有两个双引号

c++ - 动态分配数组和静态数组的区别

c++ - 指针是否保证 > 某个值?

debugging - 如何在 GDB 中获取内存地址的符号名称?

c - 使用 c 中的结构(三元组形式)添加稀疏矩阵

c - 程序经过镜像功能后重印图像

c++ - 在单独的线程中与类型的构造函数并行运行成员函数是否是未定义的行为?