简体   繁体   English

C中二维数组的分割错误

[英]Segmentation Fault for 2d array in C

The orange crosses are made from 'G' of the matrix and are valid. 橙色叉号由矩阵的“ G”制成,并且有效。 Blue ones are made from 'B' and are invalid 蓝色由“ B”制成,无效

The following code is for finding the 2 maximum areas of cross possible with equal lengths of hand from a 2D array(made from 'G' and 'B'.). 以下代码用于从2D数组(由'G'和'B'制成)中以相等的手长找到2个可能的最大交叉区域。 The cross should be made up of 'G.' 十字架应由“ G”组成。 THe following code is giving me segmentation fault while/after scanning the 2D Matrix. 以下代码在扫描2D矩阵时/扫描后给我分段错误。 Please help!! 请帮忙!!

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
int i,j,k,l,p,q;
char M[10][10];
int m, n;
int min=0;
int rl=0;
int max1=1;
int max2=1;
int area;
int tarea;
int cu=0;
scanf("%d",&n);
scanf("%d",&m);
//matrix scan
for(i=0;i<n;i++){
  for(j=0;j<m;j++){
    scanf("%c",&M[i][j]);

  }
}
 // finding first cross

for(i=0;i<n;i++){
   for(j=0;j<n;j++){
     k=j;
     l=k;
    p=i;
    q=i;
    while(M[i][k]!='B' || M[i][l]!='B' || l!=m || k!=0){
        k--;
        l++;
        rl++;
    }

    while(M[p][j]!='B' || M[q][j]!='B' || p!=0 || q!=n){
        p--;
        q++;
        cu++;
    }
    if(rl>cu){
    min=cu;
    }
    else
    min=rl;
    area=min*4+1;
    if(area>max2){
    max2=area;
    }
    if(area>max1){
    max1=area;
    }

    }
  }

tarea=max1+max2;
printf("%d",tarea);

return 0;
}

Your two while loops can very easily produce an out-of-bounds access to array M . 您的两个while循环可以很容易地产生对数组M的越界访问。 Consider, for example ... 考虑一下,例如...

while(M[i][k]!='B' || M[i][l]!='B' || l!=m || k!=0){
    k--;
    l++;
    rl++;
}

... on the first pass through the containing loop, where i , k , and l are all initially zero. ...第一次通过包含循环,其中ikl最初均为零。 Suppose further that M[0][0] has a value different from 'B' . 进一步假设M[0][0]的值不同于'B' The body of the loop will then be executed, resulting in k taking the value -1 , and then the control expression evaluated again, resulting in an attempt to read the value of M[0][-1] . 然后将执行循环的主体,导致k取值-1 ,然后再次对控制表达式求值,从而尝试读取M[0][-1] The result is undefined, but a segmentation fault -- then or later -- is entirely plausible. 结果是不确定的,但是出现分段错误(后来或以后)是完全合理的。

You need to do your bounds tests first , and you need to use && rather than || 你需要做好边界测试,你需要使用&&而非|| to ensure that the loop in fact exits when the bounds are reached. 以确保在达到界限时实际上退出循环。 It's not immediately clear to me what you want to do exactly on the edge, but here's the general idea: 对我来说,现在尚不清楚您要在边缘执行什么操作,但这是基本思路:

while((k > 0) && (l < m) && (M[i][k] != 'B' || M[i][l] != 'B')) {
    k--;
    l++;
    rl++;
}

Similar applies to your other while loop. 类似的情况也适用于您的其他while循环。

Those are not the only issues, but they are probably the ones responsible for the behavior you asked about. 这些不是唯一的问题,但可能是您所要求的行为负责的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM