如何在C++中初始化变量大小的整数数组为0?

问题描述:

当数组大小是一个变量时,如何初始化数组的所有值为零值?如何在C++中初始化变量大小的整数数组为0?

int n; 
cin >> n; 
int a[n] = {0}; 

我试过上面的代码,但它给出了一个错误。

+2

如果'n'不是'constexpr',这将无法编译,但这是如何将数组的元素初始化为零。 – 101010 2014-09-04 14:08:50

+2

请分享错误,以便我们帮助你。 – Mike 2014-09-04 14:10:02

+3

'std :: vector a(n);' – 2014-09-04 14:11:28

变长数组不是有效的C++,尽管一些编译器确实将它们实现为扩展。

C++中不允许使用变量大小的数组。可变大小意味着在程序运行时可以改变大小。上面的代码试图让用户在运行时确定大小。

所以代码不会编译。

两种选择:

1. Use Vectors 

Example: 

    vector<int> a(n,0); 

2. Create variable arrays using dynamic memory allocation. 

    int*a; 
    int n; 
    cin >> n; 
    a = new int[n]; 
    for(int i = 0; i<n;i++) 
     *(a+i) = 0; 
    delete [] a; 

// Input n 
int n; 
cin>>n; 

// Declare a pointer 
int * a; 
// Allocate memory block 
a = new int[n]; 

/* Do stuff */ 

// Deallocate memory 
delete[] a; 

更多信息请参见this tutorial