数组元素值超出数组的大小数组c设置 [英] C array setting of array element value beyond size of array
问题描述
我有这款C code段
INT号码[4] = {1};号码[0] = 1;号[1] = 2;数[3] = 3;数[10] = 4;
的printf(数字:%D%D%D \\ n,数字[0],数字[1],数字[3],数字[6],数字[10],数字[5] );
这个片段中,输出端产生:
数字:1 2 3 4 963180397 0
好吧,我有几个问题
-
设置不会号码[10]给出一个错误的数组只是大小4如果没有的话,为什么(因为它没有给出任何错误)
的 -
为什么印数[6]给出的垃圾值,而数字[5]给出0值?应该不是也有一个垃圾值。
-
什么样的影响呢设定号码[10]有我知道它不会增加数组的大小,但又有什么怎么办呢?
在此先感谢。 PS我用GCC编译code!
- 这不会给一个错误,你的数组声明堆栈上有啥数[10]的确是在ADRESS数+(10 * sizeof的INT)编写并覆盖任何东西会在那里。
- 作为Xymostech说0可以像963180397.印数[6]将打印的内容被存储在地址号码+(6 * sizeof的INT),所以它取决于你的程序的编译方式,如果你已经声明为多垃圾局部变量前的数字后,等等。 的
- 请参阅回答1。
你可以做的是这样的:
INT空[100];
INT号[4] = {1};
INT empty2 [100];memset的(空的0xCC,sizeof的空);
memset的(empty2,0xDD,sizeof的empty2);号码[0] = 1;数字[1] = 2;数字[3] = 3;数字[10] = 4;
的printf(数字:%D%D%D \\ n,数字[0],数字[1],数字[3],数字[6],数字[10],数字[5] );
现在你能理解你的号码数组访问外出时要覆盖哪些
I Have this C code snippet
int numbers[4]={1};
numbers[0]=1; numbers[1]=2; numbers[3]=3; numbers[10]=4;
printf("numbers: %d %d %d %d %d %d\n",numbers[0],numbers[1],numbers[3],numbers[6],numbers[10], numbers[5]) ;
The Output for this snippet produces :
numbers: 1 2 3 963180397 4 0
Well I have couple of questions
wont setting numbers[10] give an error as array is just of size 4 if not then why ( as it didn't give any error )
why printing numbers[6] gives garbage value whereas numbers[5] gives value of 0 ? shouldn't it also be a garbage value.
what effect does setting numbers[10] has i know it does not increases size of array but what does it do then?
Thanks in advance . PS i used GCC to compile the code!!
- This won't give an error, your array is declared on the stack so what number[10] does is write at the adress number + (10*sizeof int) and overwrites anything that would be there.
- As Xymostech said 0 can be as much garbage as 963180397. Printing numbers[6] will print what is stored at the address numbers + (6*sizeof int) so it depends on how your program is compiled, if you have declared local variables before of after numbers, etc.
- See answer 1.
What you can do is this :
int empty[100];
int numbers[4]={1};
int empty2[100];
memset(empty, 0xCC, sizeof empty);
memset(empty2, 0xDD, sizeof empty2);
numbers[0]=1;numbers[1]=2;numbers[3]=3;numbers[10]=4;
printf("numbers: %d %d %d %d %d %d\n",numbers[0],numbers[1],numbers[3],numbers[6],numbers[10], numbers[5]) ;
Now you can understand what you are overwriting when accessing out of your numbers array
这篇关于数组元素值超出数组的大小数组c设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!