Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The value of integer is changing without any calculation

I have no idea why suddenly the value of integer is changing even though there’s no process of caluclation, here’s the code of my program :

#include <iostream>
using namespace std;

int main()
{
    int n;

    int a[] = {};
    int b[] = {};

    cin >> n;
    cout << "\n";

    for(int i=0;i<n;i++)
        cin >> a[i];

    cout << "\n";

    for(int i=0;i<n;i++)
        cin >> b[i];

    cout << "\n";

    for(int i=0;i<n;i++)
        cout << a[i] << " " << b[i] << "\n";

    cout << n;
}

So if I input the value of n lower than 5, there’s no problem with the code. But if I put the value of n higher than 4, the value of integer a[i] will follow the value of b[i] somehow and the value of n is different from what I input.
As for example it’s like this
Input :

10

1
2
3
4
5
6
7
8

91
92
93
94
95
96
97
98

Output :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

95 91
96 92
97 93
98 94
5 95
6 96
7 97
8 98
8

As you can see the value of n changing from 10 to 8, and the loop only happen for 8 times. Why the value of n and a[i] are changing? Any help is appreciated, thanks

>Solution :

These declarations

int a[] = {};
int b[] = {};

invoke undefined behavior because you may not declare arrays with the number of elements equal to 0.

It seems you are trying to use variable length arrays that is not a standard C++ feature.

Nevertheless if the compiler supports this feature then you need at least to write

int n;

cin >> n;
cout << "\n";

int a[n];
int b[n];

for(int i=0;i<n;i++)
    cin >> a[i];

That is you may declare the arrays after the variable n will have a positive value.

But it is much better not to use non-standard language extensions. So instead of the variable length arrays you should use the standard container std::vector<int>.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading