C++ 将动态数组初始化为 0?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14955824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
initializing a dynamic array to 0?
提问by Luchian Grigore
int main()
{
int arraySize;
int arrayMain[arraySize-1];
cout << "\n\nEnter Total Number of Elements in Array.\n\n";
cin >> arraySize;
arrayMain[arraySize-1]={0};
cout <<"\n\n" <<arrayMain;
return 0;
}
my compiler freezes when I compile the above code. I am confused on how to set a dynamic array to 0?
当我编译上面的代码时,我的编译器冻结了。我对如何将动态数组设置为 0 感到困惑?
回答by Luchian Grigore
You use a std::vector
:
你使用一个std::vector
:
std::vector<int> vec(arraySize-1);
Your code is invalid because 1) arraySize
isn't initialized and 2) you can't have variable length arrays in C++. So either use a vector or allocate the memory dynamically (which is what std::vector
does internally):
您的代码无效,因为 1)arraySize
未初始化和 2) 在 C++ 中不能有可变长度数组。因此,要么使用向量,要么动态分配内存(这是std::vector
内部执行的操作):
int* arrayMain = new int[arraySize-1] ();
Note the ()
at the end - it's used to value-initialize the elements, so the array will have its elements set to 0.
请注意()
末尾的 - 它用于对元素进行值初始化,因此数组的元素将设置为 0。
回答by Jaydip Pansuriya
if you want to initialize whole array to zero do this ,
如果要将整个数组初始化为零,请执行此操作,
int *p = new int[n]{0};
回答by hmjd
If you must use a dynamic array you can use value initialization (though std::vector<int>
would be the recommended solution):
如果您必须使用动态数组,您可以使用值初始化(尽管std::vector<int>
这是推荐的解决方案):
int* arrayMain = new int[arraySize - 1]();
Check the result of input operation to ensure the variable has been assigned a correct value:
检查输入操作的结果以确保变量已分配正确的值:
if (cin >> arraySize && arraySize > 1) // > 1 to allocate an array with at least
{ // one element (unsure why the '-1').
int* arrayMain = new int[arraySize - 1]();
// Delete 'arrayMain' when no longer required.
delete[] arrayMain;
}
Note the use of cout
:
注意使用cout
:
cout <<"\n\n" <<arrayMain;
will print the address of the arrayMain
array, not each individual element. To print each individual you need index each element in turn:
将打印arrayMain
数组的地址,而不是每个单独的元素。要打印每个人,您需要依次索引每个元素:
for (int i = 0; i < arraySize - 1; i++) std::cout << arrayMain[i] << '\n';