数组大小小于No。存储在其中的元素的数量 [英] Array size less than the no. of elements stored in it
问题描述
是否可以声明一个大小为1的数组并能够在其中存储5个元素然后检索它们?
Is it possible to declare an array of size 1 and be able to store 5 elements in it and then retrieve them?
我尝试一个这样的代码,在其中声明了数组 arr [1]
,然后将5个元素存储到其中。实际上可以存储5个元素!
I try one such code where I declared an array arr[1]
and then stored 5 elements into it. It was actually possible to store 5 elements! How was it?
推荐答案
如果是C(或C ++),则可以轻松存储比数组大小更多的元素
If this is C (or C++), you can quite easily store more elements than the array is sized for:
#include <stdio.h>
int main (void) {
int x = 0;
int a[1]; // so that a[0] is the only valid element
a[1] = 7; // write beyond end of array
printf ("x=%d, &a[0]=%p, &a[1]=%p, &x=%p\n", x, &(a[0]), &(a[1]), &x);
return 1;
}
但是,这样做会导致行为不确定,可能会覆盖某些其他信息,并不是一个好主意。
Doing so, however, leads to undefined behaviour, probably overwriting some other piece of information, and is not really a good idea.
在我的系统上,上面的代码打印出来:
On my system, that code above prints:
x=7, &a[0]=0xbf9bb638, &a[1]=0xbf9bb63c, &x=0xbf9bb63c
尽管我将 x
设置为零,但从未明确更改它。这是因为超出数组末尾的写入已对其产生影响(如您从 a [1]
和 x )。
despite the fact I set x
to zero and never explicitly changed it. That's because writing beyond the end of the array has affected it (as you can see from the two identical addresses for a[1]
and x
).
这篇关于数组大小小于No。存储在其中的元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!