我观察到为数组分配的内存似乎是动态的。
这是我在此找到的示例代码tutorial https://www.tutorialspoint.com/data_structures_algorithms/array_data_structure.htm:
#include <stdio.h>
main() {
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
n = n + 1;
while( j >= k){
LA[j+1] = LA[j];
j = j - 1;
}
LA[k] = item;
printf("The array elements after insertion :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
和示例输出:
The original array elements are :
LA[0]=1
LA[1]=3
LA[2]=5
LA[3]=7
LA[4]=8
The array elements after insertion :
LA[0]=1
LA[1]=3
LA[2]=5
LA[3]=10
LA[4]=7
LA[5]=8
我不明白它是如何工作的。
首先,一般来说,对于没有显式大小定义并使用大括号括起来的初始值设定项进行初始化的数组,其大小将取决于初始值设定项列表中的元素。所以,对于你的数组
int LA[] = {1,3,5,7,8};
尺寸将是5
,因为您有 5 个元素。
C 使用基于 0 的数组索引,因此有效访问将为 0 到 4。
在你的代码中
LA[j+1] = LA[j];
尝试访问索引6
, (5+1
) 这是越界访问。这会调用未定义的行为 https://en.wikipedia.org/wiki/Undefined_behavior.
具有 UB 的代码的输出无论如何都不能被证明是合理的。
也就是说,main()
根据最新的 C 标准,技术上来说这是一个无效的签名。你至少需要使用int main(void)
使代码符合托管环境。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)