2017-03-04 79 views
0

我想用用户定义的大小初始化一个数组,但知道的是 - 我必须声明一个最大大小的数组,然后处理用户在此过程中给出的元素数量巨大的内存浪费。有什么办法可以声明用户给出的大小数组。 我这样做,但编译器显示错误。用户定义的数组大小

int a=0; 
std::cout<<"Enter size of array"; 
std::cin>>a; 
const int b=a; 
int ary[b]; 

我用的Turbo C++ IDE

+0

我是一个begineer所以请尝试以最简单的方式回答。 – Snigdh

+0

哪个错误来... ...? – Darshak

+1

'std :: vector ary(b);' - 为什么你使用'Turbo C++'?该编译器已有25年历史,从另一个时代开始,并且与当前的ANSI C++标准相距甚远。有很多免费的编译器是最新的。 – PaulMcKenzie

回答

2

与您的代码的问题是,您声明所谓的变长数组这不是C++(一部分,尽管它是有效的C代码)。有关为什么的解释请参见this

你可以达到你正在尝试在几个不同的方式做,但:

你可以使用用户提供的大小动态分配的数组:

#include <iostream> 
#include <memory> 

int main(int argc, char** argv) 
{ 
    std::size_t a =0; 
    std::cout<<"Enter size of array"; 
    std::cin>>a; 

    std::unique_ptr<int[]> arr(new int[a]); 
    //do something with arr 
    //the unique ptr will delete the memory when it goes out of scope 

} 

这种方法将工作,但不得总是理想的,特别是在阵列的大小可能需要频繁改变的情况下。在这种情况下,我会建议使用std::vector

#include <iostream> 
#include <vector> 

int main(int argc, char** argv) 
{ 
    std::size_t a =0; 
    std::cout<<"Enter size of array"; 
    std::cin>>a; 

    std::vector<int> arr(a);//arr will have a starting size of a 
    //use arr for something 
    //all of the memory is managed internally by the vector 
} 

您可以找到参考页here

+0

标准C++库中是否包含向量 – Snigdh

+0

是的,我提供的两种解决方案都是标准库的一部分,具体为STL(标准模板库),所有这些都是需要使用它们包括我在示例中显示的标题。 –

+0

你能解释一下吗? size_t数据类型 – Snigdh

1

您可以使用关键字同时声明动态数组

int main() 
{ 
    int array_size; 

    std::cin >> array_size; 

    int *my_array = new int[array_size]; 

    delete [] my_array; 

    return 0; 
} 

你应该删除分配的阵列。

您还可以使用向量在C++中动态分配内存。阅读here的例子载体