Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

c++ - Not trying to get random numbers for the values in my array

I am new to programming in C++. I just would like to know why this code works, giving me actual numbers:

#include <iostream>
using namespace std;

int main(){ 

    const int ARRAYSIZE = 10;
    int inc = 0;
    int arrayy[ARRAYSIZE];

    while (inc < ARRAYSIZE) {

        arrayy[inc]=inc;
        std::cout << arrayy[inc]<< endl;
        inc++;  
    }
}

But this code gives me random numbers for the values in my array:

#include <iostream>
using namespace std;

int main(){ 

    const int ARRAYSIZE = 10;
    int inc = 0;
    int arrayy[ARRAYSIZE];

    while (inc < ARRAYSIZE) {

        arrayy[inc]=inc;
        inc++;
        std::cout << arrayy[inc]<< endl;
        
    }
}
question from:https://stackoverflow.com/questions/65914354/not-trying-to-get-random-numbers-for-the-values-in-my-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the second one, you're setting a value to 0, then incrementing inc, so the value you print out is the one just after what you just set to 0. Since it hasn't been initialized (yet), it produces arbitrary ("random") values.

It also prints out the value one past the end of the array, giving undefined behavior when it does so.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...