c - int LA[] = {1,2,3,4,5} c 中的内存分配困惑

标签 c arrays loops memory

我观察到为数组分配的内存似乎是动态的。

这是我在 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/

相关文章:

输入字符后代码块崩溃,同时还执行其他一些代码

c - C/C++ 结构上的 TAG_ 前缀?

c - 为什么 .bss 显式地将全局变量初始化为零?

ruby-on-rails - 阵列::包括?在 ActiveRecord 集合上不调用 op==?

java - 如何在java中有效地使用方法中的参数?

c - 不会停止等待用户输入的游戏循环

javascript - imacros 无效的属性 ID

c - 我做错了什么错误: invalid operands to binary * (have 'float *' and 'int' )|

c++ - 如何在 C++ 中一次将 4 个字节分配给 char 数组的特定索引

c++ - 大文件中的 C++ 文件读取错误