为什么不阵列扩展? [英] Why aren't arrays expandable?

查看:115
本文介绍了为什么不阵列扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们创建一个数组,我们不能改变它的大小;它的固定。 OK,看上去不错,我们可以创建一个新的更大的阵列和复制值逐一那就是有点慢。什么是它的技术背景?

When we create an array, we cannot change its size; it's fixed. OK, seems nice, we can create a new bigger array and copy the values one by one and that's little slow. What's the technical background of it?

推荐答案

这个问题没有提及的语言,所以我要选择'C'基于阵列我的回答。

This question didn't mention a language so I'm going to choose 'C' based arrays for my answer.

数组分配为一个单独的内存块。越来越多的数组是有问题的,因为这样做正确的唯一方法是在结束时成长吧。对大小为N的生长,必须有至少N在下一分配的地址之前的数组末尾自由字节。

Arrays are allocated as a single chunk of memory. Growing an array is problematic because the only way to do it properly is to grow it at the end. For a growth of size N there must be at least N free bytes at the end of the array before the next allocated address.

支持这种类型的分配的就必须在虚拟地址空间分配为s $ P $垫。这既消除具有内存分配相互靠近的优点,并用来增加碎片。这种苍蝇在大多数内存管理器而尝试收拾起来记忆和减少碎片的面貌。

Supporting this type of allocation necessitates that allocations be spread across the virtual address space. This both removes the benefits of having memory allocations closer to each other and serves to increase fragmentation. This flies in the face of most memory managers which try to pack memory together and reduce fragmentation.

分配在有足够存储空间的一个地方一个新的数组和复制的数组根本就不是一个选项作为通用的解决方案。之所以是数组的previous位置可见通过指针到消费者身上。

Allocating a new array at a place in memory with sufficient space and copying the array there is simply not an option as a general solution. The reason why is that the previous location of the array is visible to consumers through pointers.

int* array = malloc(int*someSize);
int* pointer1 = &(arr[2]);
growArray(&array, 12);  // Can't move because pointer1 knows the address of the array

这篇关于为什么不阵列扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆