int LA [] = {1,2,3,4,5} c中的内存分配混乱 [英] int LA[] = {1,2,3,4,5} memory allocation confusion in c

查看:101
本文介绍了int LA [] = {1,2,3,4,5} c中的内存分配混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have observed that memory allocated for array seems to be dynamic.

这是我在教程中找到的示例代码:

Here is the sample code I found in this 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

我没有得到它的工作方式.

How its working I did not get.

推荐答案

首先,对于不带显式大小定义且使用大括号括起的初始化程序进行初始化的数组,这是一个通用语句,该大小将取决于初始化程序列表中的元素.因此,对于您的阵列

First, a general statement, for an array defined without explicit size and initialized using brace-enclosed initializer, the size will depend o the elements in the initializer list. So, for your array

 int LA[] = {1,3,5,7,8};

大小将为5,因为您有5个元素.

size will be 5, as you have 5 elements.

C使用基于0的数组索引,因此有效访问权限为0到4.

C uses 0-based array indexing, so the valid access will be 0 to 4.

在您的代码中

 LA[j+1] = LA[j];

正在尝试访问超出范围的索引6,(5+1).这会调用未定义的行为.

trying to access index 6, (5+1) which is out of bound access. This invokes undefined behavior.

具有UB的代码的输出不能以任何方式得到证明.

Output of a code having UB cannot be justified in any way.

也就是说,根据最新的C标准,main()从技术上来说是无效的签名.您至少需要使用int main(void)来使代码与托管环境保持一致.

That said, main() is technically an invalid signature as per latest C standards. You need to use at least int main(void) to make the code conforming for a hosted environment.

这篇关于int LA [] = {1,2,3,4,5} c中的内存分配混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆