为什么出用C绑定访问数组的? [英] Why out of bound array accessible in C?
问题描述
可能重复:结果
用C 结果数组索引越界
<一href=\"http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope\">Can一个局部变量的内存是它的范围之外访问?结果
C中没有出界失误的
我尝试这种code片段,
I am trying out this code snippet,
#include <stdio.h>
main(){
int a[2],i;
a[5] = 12;
for(i=0;i<10;i++){
printf("%d\n", a[i]);
}
return 0;
}
它给我的输出:
1053988144
32767
0
3
0
12
-1267323827
32716
0
0
为什么[5]访问?难道不应该通过运行时错误?
Why a[5] is accessible ? Shouldn't it through RunTime Error?
推荐答案
int类型的[2];
表示分配内存是 2 *的sizeof(INT)
A [5]
是语法糖 *(A + 5)
,这点面积内存 A +(5 * sizeof的(INT))
。因此, 3 * sizeof的(INT)
过去的数组的末尾。哪里是?谁知道?
a[5]
is syntactic sugar for *(a + 5)
, which point to an area of memory a + (5 * sizeof(int))
. So 3 * sizeof(int)
past the end of your array. Where is that? Who knows?
有些语言做边界检查,我也听到了一些C编译器,可以做得一样好,但大多数没有。为什么不这样做边界检查?性能。而性能是摆在首位使用C的重要原因之一。不过没关系,因为C程序员是好的程序员和的从不的超越数组的边界。 (希望)
Some languages do bound checking, and I have heard of some C compilers that can do it as well, but most do not. Why not do bound checking? Performance. And performance is a major reason for using C in the first place. But that's OK, because C programmers are good programmers and never go beyond the bounds of an array. (hopefully)
这篇关于为什么出用C绑定访问数组的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!