如何用c ++中的0初始化变量大小的整数数组?

时间:2014-09-04 14:07:49

标签: c++ arrays

当数组大小是变量时,如何用零值初始化数组的所有值?

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

我尝试了上面的代码,但它发出错误。

3 个答案:

答案 0 :(得分:3)

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;

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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