分段错误:为什么这里的数组索引越界了
Segmentation fault:Why the array index here goes out of bounds?
>我试图在这里解决问题 - 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++ 中声明数组时,其大小必须是常量表达式 - 也就是说,大小必须在编译时知道。编译器应该抱怨这些行,因为m
、n
和k
在编译时未初始化(更准确地说,初始化为不确定值(:
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] 中超出了界限,这就是错误出现的原因。
相关文章:
- 数组索引的值没有增加
- 并行用于C++17中数组索引范围内的循环
- 数组索引重载错误
- 通过指针与数组引用扩展数组索引序列
- SIGSEGV, 分段错误. 而 printf() 数组索引的值
- 缓冲区溢出 - 数组索引越界(严重)
- 为什么C++数组索引值是有符号的,而不是围绕size_t类型构建的(或者我错了)
- 查找下一个具有真值C++的数组索引
- 在编译时自动生成用于稀疏数组索引的switch语句
- 在数组索引上引发异常
- C++ 将二维数组索引与条件语句中的函数值进行比较
- 平衡数组索引,同时从左和右对数组求和
- 为什么C ,Devstudio,数组索引工作
- 如何对同一数组索引下的结构成员进行排序?
- 我想返回数组索引,而不是数组值
- C++相当于 Python 的:用于数组索引
- 分段错误:为什么这里的数组索引越界了
- 数组索引在地图上不是整数
- 根据用户输入的每个字母添加到数组索引
- C 数组索引