【问题标题】:Defining an array size with a variable in a structure使用结构中的变量定义数组大小
【发布时间】:2012-11-14 11:46:07
【问题描述】:

我之前尝试过在 C++ 中使用变量定义数组大小,虽然我不完全理解动态内存的概念,但我成功了。但是,在这种情况下,我不知道如何对数组 'point' 做同样的事情。

num=50;
struct pos
{
double x;
};

 struct pos point[num]; 

有什么明显的我忽略的吗?

【问题讨论】:

  • 数组在标准 C++ 中不能具有动态大小。
  • 有什么明显的我忽略了吗? std::vector

标签: c++ struct dynamic-memory-allocation


【解决方案1】:

这些类型的数组大小必须是编译时常量,因此编译器知道要保留多少内存。

int count = 50;
int arr[count] // error!

static const int count = 50;
int arr[count]; // OK!

另一个选项是动态分配的内存,其大小在运行时是已知的。

int count = 50;
int* arr = new int[count];
delete [] arr;

但是,通常您不希望自己处理原始指针和内存分配,而应该更喜欢:

#include <vector>

int count = 50;
std::vector<int> arr(count);

这也适用于您提供的任何可复制的自定义类型(提示:您的示例 pos 结构是可复制的):

#include <vector>

int count = 50;
std::vector<pos> arr(count);

arr[0].x = 1;
// ... etc
arr[49].x = 49;

std::vector界面丰富,所有细节can be found here

【讨论】:

  • 如果不想要vector 的功能,另一种选择是使用unique_ptr&lt;int[]&gt; arr( new int[count]; )
  • 是的,我很高兴 unique_ptr 解决了 auto_ptr 无法正确处理数组的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
  • 2020-09-03
  • 1970-01-01
  • 2018-09-01
  • 2010-09-15
相关资源
最近更新 更多