数组和动态数组有什么区别?
下面两种类型的数组有什么区别?
int array1[10];
int* array2 = new int[10];
What is the difference between the following two types of array?
int array1[10];
int* array2 = new int[10];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
主要区别在于动态数组是在堆上创建的。动态数组的大小可以在运行时确定。
下面的区别
是: array2 指向数组的第一个元素,而不是实际的完整数组。
注意:
使用 new 创建的堆上的内存最终应使用
delete
销毁。由于
array2
是在堆上创建的,并且是一个数组,因此您需要使用delete[]
删除它。注意:您实际上可以创建一个指向完整数组的指针,而不仅仅是第一个元素:
但是它们指向的大小不同:
The main difference is that a dynamic array is created on the heap. A dynamic array's size can be determined at runtime.
The difference in the below:
Is that
array2
is pointing to the first element of an array and not the actual full array.Note:
Memory on the heap that is created with new should eventually be destroyed using
delete
.Since
array2
is created on the heap, and is an array you will need to delete it withdelete[]
though.Note: You can actually create a pointer to a full array and not just the first element:
However what they point to have different sizes:
动态数组是在运行时从堆内存创建的,并且可以根据需要使用 new/delete 关键字动态调整大小/释放。数组在编译时静态定义,并且始终占用该内存量。
A dynamic array is created from heap memory at run time and can be dynamically resized/freed as necessary with the new/delete keywords. An array is statically defined at compile time and will -always- take that amount of memory at all times.