我目前正在使用C语言操作数组,我对为什么在与数组相关的操作中通常使用dim-1感到有点困惑.如果dim指定了数组中的数据量,使用dim-1不会潜在地导致丢失一个元素吗?
例如,在冒泡排序算法的上下文中,通常使用:
for (int i = 0; i < dim - 1; i++)
.
这次大会有什么特别的原因吗?
我是通过将索引初始化为1还是将其设置为DIM-1来丢失元素?
我试着不使用这个约定,它似乎也能正常工作,但它被标记为不正确.
我目前正在使用C语言操作数组,我对为什么在与数组相关的操作中通常使用dim-1感到有点困惑.如果dim指定了数组中的数据量,使用dim-1不会潜在地导致丢失一个元素吗?
例如,在冒泡排序算法的上下文中,通常使用:
for (int i = 0; i < dim - 1; i++)
.
这次大会有什么特别的原因吗?
我是通过将索引初始化为1还是将其设置为DIM-1来丢失元素?
我试着不使用这个约定,它似乎也能正常工作,但它被标记为不正确.
你是对的.为大小为dim
的数组中的每个元素执行或判断某些操作的循环通常被编程为for (int i = 0; i < dim; i++)
,它可以让您每次迭代一次,并为i
提供适合于寻址每个数组元素的值.(当然是基于0的,即从索引0开始.
But many algorithms, notable the bubble sort which you are mentioning, look at each possible pair of neighboring elements. I.e. you look at each i
and at i+1
as index, through the whole array. But doing that you need to stop BEFORE the last usually available i
(being dim-1
), because you cannot use dim -1 +1
for the other part of the last pair. So the last pair is dim-2
and dim-1
.
A loop that will allow you in each iteration to access i
and i+1
and end up using dim-2
and dim-1
is
for (int i = 0; i < dim - 1; i++)
个
这就是为什么.
(这非常接近詹姆斯·K·波尔克总统的 comments ,但我认为将 comments 转化为答案是可以的,我对此进行了实质性的扩展.此外,我在意识到这条 comments 存在之前也打了字,但这可能不是一个借口……:-))