如何在 C 中创建动态整数数组?
如何使用 new
关键字在 C++ 中创建动态整数数组?
How to create a dynamic array of integers in C++ using the new
keyword?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何使用 new
关键字在 C++ 中创建动态整数数组?
How to create a dynamic array of integers in C++ using the new
keyword?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(8)
不要忘记
删除
使用new
分配的每个数组。Don't forget to
delete
every array you allocate withnew
.从 C++11 开始,有一个安全的替代方案来替代
new[]
和delete[]
,与std::vector
不同,它是零开销的:在 C++14 中:
以上两者都依赖于相同的头文件,
#include
Since C++11, there's a safe alternative to
new[]
anddelete[]
which is zero-overhead unlikestd::vector
:In C++14:
Both of the above rely on the same header file,
#include <memory>
您可能需要考虑使用标准模板库。它简单易用,而且您不必担心内存分配。
http://www.cplusplus.com/reference/stl/vector/vector/
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/
一旦问题涉及动态数组,您可能不仅想要创建具有可变大小的数组,而且还想要在运行时更改其大小。这是一个使用
memcpy
的示例,您也可以使用memcpy_s
或std::copy
。根据编译器的不同,可能需要
或
。使用此函数时,您分配新的内存区域,将原始内存区域的值复制到其中,然后释放它们。您可以使用常量 4 代替
sizeof(int)
。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 usememcpy_s
orstd::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.You may use constant 4 instead of
sizeof(int)
.使用
new
动态分配一些内存:dynamically allocate some memory using
new
:上面的答案都适合分配一维 int 数组。无论如何,我想补充一点,对于通常定义的多维数组也可以执行此操作,如
int[][] matrix = {{1,2}, {3,4}}.
关键是将所有元素存储在一个数组中,并利用数组是内存中的连续块这一事实(请参阅此处< /a> 来澄清“块”),这意味着你可以通过维度“切片”自己。下面您可以看到二维数组的示例。
您可以在此处<找到有关此主题的讨论< /a> 就这样。
填充此类矩阵对象的示例如下:
The answers above are all good for assigning one-dimensional int-arrays. Anyhow, I want to add that it is also possible to do this for multi-dimensional arrays you'd normally define like
int[][] matrix = {{1,2}, {3,4}}
.The key is that you store all elements in one array and make use of the fact that the array is a continuous block in memory (see here for a clarification of "block"), meaning that you can "slice" yourself through dimensions. Below you can see an example for a 2d-array.
You can find a discussion regarding this topic here on SO.
An example to populate such a
Matrix
-object would be:上面的代码有效,可以定义的最大 float 或 int 数组大小为 2095879,退出条件将为非零开始输入数字
The above code works, the maximum float or int array size that could be defined was with size 2095879, and exit condition would be non zero beginning input number