我观察到为数组分配的内存似乎是动态的。
这是我在 tutorial 中找到的示例代码:
#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
),这是越界访问。这会调用 undefined behavior .
无法以任何方式证明具有 UB 的代码的输出。
也就是说,根据最新的 C 标准,main()
在技术上是无效的签名。您至少需要使用 int main(void)
来使代码符合托管环境。
关于c - int LA[] = {1,2,3,4,5} c 中的内存分配困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39484391/