Here I am declaring array length before taking input for n. At the time of array declaration n=0.
#include <iostream>
using namespace std;
int main() {
int n;
int sum=0;
int arr[n]={};
cin >> n;
for(int i=0;i<n;i++) {
cin >> arr[i];
cout << arr[i];
}
return 0;
}
for below input 6 1 2 3 4 5 6
I am getting this output 1234.
Can someone please explain the reason?
nwould be zero?int arr[n]={};, it's not valid in the standard C++ as the length must be known at compile-time. You should be usingstd::vectorinstead.nis uninitialized and could have any other value, and reading from it causes undefined behavior.