分段错误:为什么这里的数组索引越界了

Segmentation fault:Why the array index here goes out of bounds?

本文关键字:数组 索引 越界 这里 错误 为什么 分段      更新时间:2023-10-16

>我试图在这里解决问题 - https://www.codechef.com/APRIL19B/problems/FENCE 并将数组初始化为 0,但是当我尝试使用 n=4 和 m=4 访问 arr[0][4] 处的值时,它会打印一个垃圾值。

我尝试使用向量思维进行初始化,我在数组初始化中犯了一些错误,它适用于示例测试用例,但仍然给出分割错误。

这是我的代码 -

#include<bits/stdc++.h>
#include <iostream>
using namespace std;
int main() {
    // your code goes here
    int t;
    cin>>t;
    while(t--){
        long long n,m,k,res=0;
        cin>>n>>m>>k;
        //vector<vector<long long>> arr(n+2,vector<long long>(m+2,0));
        long long arr[n+2][m+2]={0};
        long long vec[k][k];
        for(unsigned int it=0;it<k;it++){
            int t1,t2;
            cin>>t1>>t2;
            arr[t1][t2]=1;
            vec[it][0]=t1;
            vec[it][1]=t2;
        }
        cout<<"values:"<<arr[1][4]<<endl;
        for(unsigned int itr =0;itr<k;itr++){
            int j = vec[itr][0];
            int i = vec[itr][1];
            //cout<<i<<" "<<j<<endl;
            res+=4-(arr[i-1][j]+arr[i+1][j]+arr[i][j-1]+arr[i][j+1]);
        }
        cout<<res<<endl;
    }
    return 0;
}

编辑:示例输入为:

Example Input
2
4 4 9
1 4
2 1 
2 2
2 3
3 1
3 3
4 1
4 2
4 3
4 4 1
1 1
Example Output
20
4

约束条件:

  1≤T≤10 
  1≤N,M≤10^9
  1≤K≤10^5
  1≤r≤N
  1≤c≤M
  the cells containing plants are pairwise distinct

我希望第一个测试用例的输出为 - 20,但得到垃圾值。

在 C++ 中声明数组时,其大小必须是常量表达式 - 也就是说,大小必须在编译时知道。编译器应该抱怨这些行,因为mnk在编译时未初始化(更准确地说,初始化为不确定值(:

long long arr[n+2][m+2]={0};
long long vec[k][k];

我认为数组在 arr[i-1][j] 或 arr[i+1][j] 或 arr[i][j+1] 或 arr[i][j-1] 中超出了界限,这就是错误出现的原因。