[Other] An Overview of Arrays and Memory

本文深入探讨了整型变量在内存中占用的空间大小,解释了一个整型变量占用32位即4字节的原因。进一步分析了数组在内存中的存储方式,以及当数组需要扩容时,如何通过创建新的更大数组并删除旧数组来实现。文章还讨论了在存在其他变量的情况下,简单地在原有数组后追加内存的不可行性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

One integer takes 32bit in memory, 1 byte = 8bits, therefore one integer takes 4 bytes.

Now let's assume we have an array: [1,2,3]

  4bytes .   4bytes .  4bytes

| . | . | . | . | . | . | . | . | . | . | . | . |

     1 .            2 .          3

It tooks 4 * 3 bytes for three integers in an array. What if we want to add two more integers into the array, how the memory allocate?

   A. it appends another 8 bytes in the end

   B. it recreate an new array with 4 * 5 bytes size. 

 

B. is the correct answer. It always create a new larger array and delete the old array. The simple reason for this is because we never know after array, it might have other code:

var a = [1,2,3]
var c = 4

  4bytes .   4bytes .  4bytes     4bytes

| . | . | . | . | . | . | . | . | . | . | . | . | . | . | . | . |

     1 .            2 .          3 .        c=4

It assign 4 bytes to variable c in memory. We cannot simply append more memory after the old array. 

 

转载于:https://www.cnblogs.com/Answer1215/p/10236848.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值