vscode c++ 中的分段错误

Segmentation fault in vscode c++

我正在 macOS vscode 上编写一个简单的线性搜索程序。 该代码仅在 vscode 中产生称为分段错误的错误。 但奇怪的是,代码在 onlinegdb 编译器和 Xcode IDE 上运行得非常好。 我在 Mac 上安装了默认的 c++ 编译器,它是在安装 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]

[1]: https://i.stack.imgur.com/Bo3Nu.png

段错误不是 vscode 错误,它是一个程序错误,它表明您的程序正在访问它未保留的内存地址,因此 OS 终止了您的程序使系统免于错误或错误的内存访问。

你先用0初始化n,然后用n个整数初始化数组arr。所以它使你成为一个 0 整数的数组。如果你想完成这项工作,请将 int arr[n] 推到 cin >> n 下方。您必须首先使用 stoi()

将其从字符串转换为 int

图书馆:

#include <string>
#include <iostream>

代码:

//Create the int to store the length of the array
int n = 0;
//A string, beacause cin returns a string
std::string s;

//Get the number
std::cout << "Length of array: ";
std::cin >> s;

//Convert the string to an int
n = stoi(s);

//Create the array
int arr[n];