甚至在开始执行之前出现分段错误

Segmentation Fault before even starting execution

本文关键字:分段 错误 开始 执行      更新时间:2023-10-16

我昨天在codeforce的现场比赛中写了这段代码,甚至在main((中执行第一行之前就产生了分割错误。 该程序甚至没有打印"测试">

#include <bits/stdc++.h>
using namespace std;
int main () {
cout << "test";
int t;
cin >> t;
while (t--) {
int n, s, k, ans = 0;
cin >> n >> s >> k;
int arr[n+1];
memset(arr, 0, sizeof arr);
for (int i = 0; i < k; i++) {
cin >> t;
arr[t] = 1;
}
int i = 0;
while (true) {//cout<<"test";
if (s+i <= n && arr[s+i] == 0) break;
if (s-i > 0 && arr[s-i] == 0) break;
if (s-i <= 0 && s+i > n) break;
i++;
}
cout << i << endl;
}
return 0;
}

您的程序不会打印"test",因为您需要刷新标准输出。如果不刷新它,SO 会将该文本保存在缓冲区中,并可能等待适当的时刻将其输出。相反,强制 SO 使用以下方法打印它:

cout << "test" << std::endl;

flush(stdout);