我正在 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]
分段错误不是 vscode 错误,而是程序错误,它表明您的程序正在访问未保留的内存地址,因此操作系统会杀死您的程序以保护系统免受错误或错误的内存访问。
首先用 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];
给你,
#include <iostream>
#include <sring>
using namespace std;
int n = 0;
string s;
//Get the number
cout << "Length of array: ";
cin >> s;
n = stoi(s);
int arr[n];
除此之外,只需检查其他程序的 dll 是否被加载,有时它们也会干扰程序的运行并导致分段错误。 就像有一次我在 vscode 中编写了一个简单的 c++ 程序,当我编译并运行我的程序时,它从 Windows 上的某个已安装程序中获取 dll,该程序具有 c++ 标准库 (std::),因此它导致运行时错误,如下所示分段故障。 因此,我从 Windows 环境路径变量中删除了导致冲突的程序的路径,并且我的程序运行没有任何错误。