Close
Close

Why display an user input array by For-each loop got additional unknown values when execute the program?

   Shiyu Shuai

My code is below:

#include<iostream>
using namespace std;

int main()

    int size;
    int arr[size];
    cout<<"Please set array size: "<<endl;
    cin>>size;
    for(int i=0;i<size;++i)
    {
        cout<<"Num "<<i+1<<" is: ";
        cin>>arr[i];
    }
    for (int m : arr)
    {
        cout << m << endl;
    }
    return 0;
}

Out put is below (set array size to 2, input values are “1” and “2”)

Please set array size:

2

Num 1 is: 1

Num 2 is: 2

1

2

4199840

0

5471808

0

1

0


Answers

  •   

    The iteration format you used to create the array isn’t the same style as the one you used to read from it. Since the one used to read/output values are based on a pointer to a memory location, you are likely reading out of bound. C++ does not have out of bound mechanism for this. So you got no errors. You continued to read the data on the memory location as long as there are m: arr. If you want to produce the correct output you may have to give the proper boundaries of the array. for (int i=0; i<arrsize; i++){...}.


    • Thank you so much for your answer.
      - Shiyu Shuai

Ask Yours
Post Yours
Write your answer