I am writing a simple program of linear search on vscode on macOS. The code is producing an error called segmentation fault only in vscode. But the strange thing is that code is working perfectly fine on onlinegdb compiler and Xcode IDE. I have the default c++ compiler installed on my Mac which came after installing Xcode.
#include<iostream>
using namespace std;
int linearSearch(int arr[], int n, int key){
int i = 0;
for(i = 0; i<n;i++)
{
if(arr[i] == key){
return i;
}
} return -1;
}
int main(){
int n = 0;
int arr[n];
int key = 0;
cout<<"Enter the length of the array"<<endl;
cin>>n;
cout<<"Enter the elements of the array"<<endl;
int i = 0;
for(i = 0; i<n;i++)
{
cin>>arr[i];
}
cout<<"Enter the element to search in array"<<endl;
cin>>key;
cout<<linearSearch(arr, n, key);
}[screenshot of the error in vscode][1]