C++ 如何创建一个动态整数数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4029870/
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
How to create a dynamic array of integers
提问by Sudantha
How to create a dynamic array of integers in C++ using the new
keyword?
如何使用new
关键字在 C++ 中创建动态整数数组?
回答by Jason Iverson
int main()
{
int size;
std::cin >> size;
int *array = new int[size];
delete [] array;
return 0;
}
Don't forget to delete
every array you allocate with new
.
不要忘记delete
使用new
.
回答by Ben Voigt
Since C++11, there's a safe alternative to new[]
and delete[]
which is zero-overhead unlike std::vector
:
从 C++11 开始,有一个安全的替代方案new[]
,delete[]
它是零开销的,不像std::vector
:
std::unique_ptr<int[]> array(new int[size]);
In C++14:
在 C++14 中:
auto array = std::make_unique<int[]>(size);
Both of the above rely on the same header file, #include <memory>
以上两者都依赖同一个头文件, #include <memory>
回答by jveazey
You might want to consider using the Standard Template Library . It's simple and easy to use, plus you don't have to worry about memory allocations.
您可能要考虑使用标准模板库。它简单易用,而且您不必担心内存分配。
http://www.cplusplus.com/reference/stl/vector/vector/
http://www.cplusplus.com/reference/stl/vector/vector/
int size = 5; // declare the size of the vector
vector<int> myvector(size, 0); // create a vector to hold "size" int's
// all initialized to zero
myvector[0] = 1234; // assign values like a c++ array
回答by Ed S.
int* array = new int[size];
回答by carimus
As soon as question is about dynamic array you may want not just to create array with variable size, but also to change it's size during runtime. Here is an example with memcpy
, you can use memcpy_s
or std::copy
as well. Depending on compiler, <memory.h>
or <string.h>
may be required. When using this functions you allocate new memory region, copy values of original memory regions to it and then release them.
一旦问题与动态数组有关,您可能不仅希望创建具有可变大小的数组,而且还希望在运行时更改其大小。这是一个带有 的示例memcpy
,您也可以使用memcpy_s
或std::copy
。取决于编译器,<memory.h>
或者<string.h>
可能需要。使用此函数时,您分配新的内存区域,将原始内存区域的值复制到其中,然后释放它们。
// create desired array dynamically
size_t length;
length = 100; //for example
int *array = new int[length];
// now let's change is's size - e.g. add 50 new elements
size_t added = 50;
int *added_array = new int[added];
/*
somehow set values to given arrays
*/
// add elements to array
int* temp = new int[length + added];
memcpy(temp, array, length * sizeof(int));
memcpy(temp + length, added_array, added * sizeof(int));
delete[] array;
array = temp;
You may use constant 4 instead of sizeof(int)
.
您可以使用常量 4 而不是sizeof(int)
。
回答by Montdidier
dynamically allocate some memory using new
:
动态分配一些内存使用new
:
int* array = new int[SIZE];