当前位置:网站首页>为什么数组的下标都是从0开始而不是1?
为什么数组的下标都是从0开始而不是1?
2022-04-22 05:34:00 【新猿一马】
目录
一 数组寻址公式
a[i]_address = base_address + i * data_type_size
data_type_size 是数组中每一个元素大小。
二 数组模型表示
以 int[] a = new int[10] 为例。计算机给数组 a[10],分配了一块连续内存空间 2000~2039,内存块的首地址为 base_address = 2000。

三 数组寻址计算
假设数组从0开始,计算第9个元素公式是:a[9]_address = 2000 + 9 * 4 = 2036;
假设数组从1开始,计算第9个元素公式是:a[9]_address = 2000 + (10-1) * 4 = 2036
对比:数组从1开始相当于每次随机访问数组元素都多了一次减法运算,对于 CPU 来说,就是多了一次减法指令。数组作为非常基础的数据结构,通过下标随机访问数组元素又是其非常基础的编程操作,效率的优化就要尽可能做到极致。
结论:为了减少一次减法操作,数组选择了从 0 开始编号,而不是从 1 开始。
版权声明
本文为[新猿一马]所创,转载请带上原文链接,感谢
https://blog.csdn.net/jack1liu/article/details/120380817
边栏推荐
猜你喜欢

C language version: the pre order, middle order and post order non recursive traversal of binary tree
![[nanny installation tutorial] download MySQL 5 from the source code of Linux operating system seven](/img/1a/f2b3da4aa6df9deccf2d1376744b7a.png)
[nanny installation tutorial] download MySQL 5 from the source code of Linux operating system seven

枚举和Lambda表达式

Strong connected component of "tarjan" undirected graph

Pratique du langage C (2) - - mise en oeuvre de l'addition polynomiale par liste liée

AcWing 836. 合并集合(并查集)

MySQL 第6章 Navicat 的安装与使用

Unsafe row of spark

Application and selection of it power distribution and fire current limiting protector

MySQL JDBC programming
随机推荐
Integer source code
MySQL 第7章 对数据表的复杂查询
Kaggle_ Detailed explanation of NBME NLP competition baseline (2)
Read write separation of MYCAT
环形链表2
Pratique du langage C (2) - - mise en oeuvre de l'addition polynomiale par liste liée
Fundamentals of graphics - Mobile GPU architecture
@PostConstruct方法内部死循环引起的问题
C语言期中复习训练
POI 和 EasyExcel练习
C language version: traversal mode and reverse order of binary tree
DolphinDB VSCode 插件使用教程
fastjson判断JSON字符串是Object还是List<Object>
MySQL Basics
C language version: the establishment and basic operation of chain stack
2022.4.21-----leetcode.824
供应链服务术语
7.Domino piling
Mysql基础知识
MySQL索引