数组和动态数组有什么区别?

发布于 2024-08-23 13:32:25 字数 91 浏览 7 评论 0原文

下面两种类型的数组有什么区别?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

神经大条 2024-08-30 13:32:25

主要区别在于动态数组是在堆上创建的。动态数组的大小可以在运行时确定。

下面的区别

int x = 10;
int array1[10];
int *array2 = new char[x];

是: array2 指向数组的第一个元素,而不是实际的完整数组。

注意:

assert(sizeof(array1) == 40);
assert(sizeof(array2) == 4);

使用 new 创建的堆上的内存最终应使用 delete 销毁。
由于 array2 是在堆上创建的,并且是一个数组,因此您需要使用 delete[] 删除它。

注意:您实际上可以创建一个指向完整数组的指针,而不仅仅是第一个元素:

int array1[10];
int *pointerToFirstElement = array1;
int (*pointerToFullArray)[10] = &array1;
int sizeOfFirstPointer = sizeof(pointerToFirstElement);
int sizeOfSecondPointer = sizeof(pointerToFullArray);
assert(sizeOfFirstPointer == sizeOfSecondPointer);//==4 since both are pointers

但是它们指向的大小不同:

int sizeOfFirst = sizeof(*pointerToFirstElement);
int sizeOfSecond = sizeof(*pointerToFullArray);
assert(*sizeOfFirst == 4);
assert(*sizeOfSecond == 40);

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:

int x = 10;
int array1[10];
int *array2 = new char[x];

Is that array2 is pointing to the first element of an array and not the actual full array.

Note:

assert(sizeof(array1) == 40);
assert(sizeof(array2) == 4);

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 with delete[] though.

Note: You can actually create a pointer to a full array and not just the first element:

int array1[10];
int *pointerToFirstElement = array1;
int (*pointerToFullArray)[10] = &array1;
int sizeOfFirstPointer = sizeof(pointerToFirstElement);
int sizeOfSecondPointer = sizeof(pointerToFullArray);
assert(sizeOfFirstPointer == sizeOfSecondPointer);//==4 since both are pointers

However what they point to have different sizes:

int sizeOfFirst = sizeof(*pointerToFirstElement);
int sizeOfSecond = sizeof(*pointerToFullArray);
assert(*sizeOfFirst == 4);
assert(*sizeOfSecond == 40);
一人独醉 2024-08-30 13:32:25

动态数组是在运行时从堆内存创建的,并且可以根据需要使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文