为什么有时可以超出范围调用数组 [英] Why arrays can be invoked out of bounds sometimes

查看:51
本文介绍了为什么有时可以超出范围调用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个 C 代码:

#include <stdio.h>
int main()
{
 int i;
 int a[4];
  for( i =0;i<5;i++)
 {
  a[i]=i;
  printf("a[%d]:%d ",i,a[i]);

  }
 return 0;
 }

我用gcc编译并成功运行,结果是:

I used gcc to compile it and succeed to run,the result is :

a [0]:0 a [1]:1 a [2]:2 a [3]:3 a [4]:4

a[0]:0 a[1]:1 a[2]:2 a[3]:3 a[4]:4

但是您可以看到数组 a 的大小为4,从0到3,我没有创建额外的内存来引用 a [4] ,并且意外地它运行并且似乎没有错误.在 Java 中,我发现数组的索引是否超出范围,它将引发异常.我只是不知道为什么在C语言中它会像正确的那样运行.

But you can see array a has size of 4,from 0 to 3,i haven't create extra memory to refer to a[4],and unexpectedly it run and seem no errors.In Java,i find if arrays' index out of bounds,it'll throws exception.I just don't know why in C language it just run like right.

推荐答案

C不检查数组边界.分段错误只会在您无法读写程序的情况下发生.仅仅超越数组边界不会使您的程序崩溃.

C doesn't check array boundaries. Segmentation fault will only happen when you read or write to memory your program don't have access to. Simply going past array boundaries won't make your program crash.

但是超出范围访问索引会调用未定义的行为.

But accessing index out of bounds invokes undefined behaviour .

这篇关于为什么有时可以超出范围调用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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