-1

i am running this code in online compiler showing dumped core error this program finding highest product of two pair.

#include <bits/stdc++.h>
using namespace std;
void maximumproductpair(int arr[],int n){
sort(arr,arr+n);
reverse(arr,arr+n);
int prod;
for(int i=0; i<n; i++){
cout<<arr[i];
}
prod=prod*arr[0];
prod=*arr[1];
cout<<prod;
}

int main() 
{
int t,n;
int arr[n];
cin>>t;
cout<<"\n";
cin>>n;
cout<<"\n";
  while(t--){
  for(int i=0; i<n;i++){
  
     cin>>arr[i];
   }
 }
maximumproductpair(arr,n);
  return 0;
}

in code everything fine then why this error?

1 Answers1

0

Mistake 1

The problem is that your t and n variables are uninitialized. This means both t and n have garbage value. And when you wrote:

int t,n;
int arr[n];//UNDEFINED BEHAVIOR because n has garbage value

You have undefined behavior because n has garbage value.

This is why it is advised that

always initialize built in types in local/block scope.

Mistake 2

Second, note that in C++ the size of an array must be a compile-time constant. So take for example the following code snippets:

int n = 10;
int array[n]; //INCORRECT

The correct way to write the above would be:

const int n = 10;
int array[n]; //CORRECT 

Similarly,

int n;
cin >> n;
int array[n]; //INCORRECT becasue n is not a constant expression

Also note that some compilers provide compiler extension that lets you have variable length array. You can read more about it at Why aren't variable-length arrays part of the C++ standard?.

If you want to take the size of the array as input from the user then you should use dynamic sized containers like std::vector :

int n;
cin >>n;
std::vector<int> array(n);// CORRECT, this creates a vector of size n of elements of type int

Also see Why should I not #include <bits/stdc++.h>?.

Jason
  • 36,170
  • 5
  • 26
  • 60
  • Thanks but taking input from user does not show any error even without using const itself. – igneous spark Dec 12 '21 at 08:36
  • @igneousspark Yes you do not see any error because some compilers(like the one you're using) provide **compiler extension** that lets you write `int n; cin >> n; int arr[n];`. This is why you do not see error because the compiler you are using provides an extension that lets you do that. It's just that it is **not standard C++**. Read more about it [here](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – Jason Dec 12 '21 at 08:38