除非所有字段都初始化为0,否则int数组会给出疯狂的值,为什么? [英] int array gives crazy values unless all fields initialized to 0, why?

查看:82
本文介绍了除非所有字段都初始化为0,否则int数组会给出疯狂的值,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int TwoThrows();


int main(){

        int Throws, Throw, Frequency[13]={0,0,0,0,0,0,0,0,0,0,0,0,0};
        randomize();


        cout << "\nThis program simulates throws of two dice.";
        cout << "\n\nHow many throws : ";
        cin >> Throws;



        // Calls TwoThrows and saves in Frequency by value
        for(int I=0; I<Throws; I++){
                Throw=TwoThrows();   //2-12
                Frequency[Throw]++;   //2-12

        }

         // Prints array:
        for(int I=0; I<11; I++){
                cout << I+2 << ":\t" << Frequency[I+2] << "\n";

        }

        return 0;
}

int TwoThrows(){
        unsigned int I=(random(6)+1)+(random(6)+1);

        return I;

}

此打印:

2:1317
3:2724
4:4145
5:5513
6:7056
7:8343
8: 6982
9:5580
10:4176
11:2776
12:1388

2: 1317 3: 2724 4: 4145 5: 5513 6: 7056 7: 8343 8: 6982 9: 5580 10: 4176 11: 2776 12: 1388

哪个很棒。

但是,我想知道的是,为什么必须将数组设置为{0,0,0,0,0,0,0,0,0, 0,0,0,0}?

However, what I want to know is, why did I have to set the array to {0,0,0,0,0,0,0,0,0,0,0,0,0}?

如果我不这样做的话;我得到:

If I do NOT do that; i get:

2:30626868
3:1638233
4:844545295
5:1
6:9
7:4202510
8:4199197
9:844555757
10:3
11:4202574
12:2130567168

2: 30626868 3: 1638233 4: 844545295 5: 1 6: 9 7: 4202510 8: 4199197 9: 844555757 10: 3 11: 4202574 12: 2130567168

推荐答案

如果不初始化数组,然后继续增加其元素,从技术上讲,这是未定义的行为

If you don't initialize the array, and then proceed to increment its elements, technically this is undefined behaviour.

在实践中发生的事情是,数组的元素得到的值恰好等于 main()启动时堆栈。

What happens in practice is that the array's elements get whatever values happen to be on the stack when main() starts.

这篇关于除非所有字段都初始化为0,否则int数组会给出疯狂的值,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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