A C++ Program which works fine in online compilers and linux operating systems, but not on Windows
While compiling a problem:
Geeks For Geeks: First Repeating Element on a Windows operating system I noticed that I was not getting any output for my solution. But when I compiled the same code on a Linux operating system and on online compilers, it worked absolutely fine without producing any errors.
Code:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin>>n;
int arr[n];
for(int i=0; i <n; i++) {
cin>>arr[i];
}
int size= 1e6+1; // WA on windows
int A[size];
int min_index=INT_MAX;
for(int i=0; i<size; i++) {
A[i]=-1;
}
for(int i=0; i<n; i++) {
if(A[arr[i]]!=-1)
min_index=min(min_index, A[arr[i]]);
else
A[arr[i]]=i;
}
if(min_index==INT_MAX)
cout<<"-1";
else
cout<< min_index+1;
return 0;
}
Sample Test Case:
7
1 5 3 4 3 5 6
Expected output:
2
Output on Windows: Screenshot
Output on Linux: Screenshot
Explanation for the program from line 14 of code:
I created an array A
of size 1e6+1
to store value i
on its arr[i]
th index.
Array A
was earlier initialized with value -1
. It runs for n
number of times and variable min_index
stores the index of the least repeating number from the array arr
.
After initializing smaller values of array int size = 10
and using very small test cases(also max value of arr[i] is lesser than size of A
; I realize that the program runs perfectly in Windows.
As far as I understand, Windows might be having some trouble intializing arrays of such large length (Please correct me if I'm wrong). But why isn't it the same in the case of Linux?
Solution 1:
#include <bits/stdc++.h>
is not standard C++, hence you should not expect it to be portable.
int arr[n];
is not standard C++. Some compilers offer variable length arrays as extension, but it isnt portable. Same goes for int A[size];
.
Sadly most of the C++ code presented on that site is not proper C++ code but some dialect.
For more details see: Why should I not #include <bits/stdc++.h>? and Why aren't variable-length arrays part of the C++ standard?. That Q&As should also explain the standard portable alternatives.