为结构动态分配内存
Dynamically allocating memory for structures
>我正在尝试动态分配一个结构,并且需要知道我是否做得对。 根据我的书,我是。 但是我的编译器给了我一个错误。 以下是相关代码:
#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++中动态分配的内存(数组对象)
- 删除类成员的动态分配内存的最佳方法是什么
- 动态分配的内存构造函数
- 为什么动态分配的内存总是16字节对齐
- 如果您为类的一个对象动态分配内存作为参数,会发生什么
- 为什么动态分配的两个变量的内存位置不是连续的?
- 为浮点数组动态分配内存
- 动态分配 8 字节的内存
- 包含动态分配内存作为值的映射的取消定位速度有多快?
- STD分配器是否会在堆上动态分配内存?它可以安全地删除内存吗?
- 为什么不能在 Visual C++ 中动态分配堆栈内存?但海湾合作委员会可以做到
- 在C 中动态分配的内存的问题
- 为什么在 C++ 执行删除操作后仍可以访问释放的动态分配的内存
- 对内存动态分配的类不使用"*"的逻辑
- 如果我将内存动态分配给静态变量,我应该释放它还是会自动释放它