The code gives segmentation error, how? [closed]
#include`<stdio.h>`
#include`<stdlib.h>`
int main()
{
int k, i, j,tot=0, htot=0, vtot=0, dtot=0, m, n;
int 开发者_运维技巧a[8][8] = {
{0,0,0,0,0,0,1,0},
{0,0,0,1,0,0,0,0},
{0,1,0,0,0,0,0,0},
{1,0,0,0,0,0,0,0},
{0,0,1,0,0,0,0,0},
{0,0,0,0,0,1,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,0,0,0,0,1},
};
for(i=0;i<8;i++)
{
htot=0;
printf("\n");
for(j=0;j<8;j++)
{
htot += a[i][j];
printf("%d\t", a[i][j]);
}
tot += htot ;
}
if(tot == 8)
printf("Moving on to Vertical checking");
else
printf("Horizontal criterion not fulfilled %d ", tot);
tot=0;
for(j=0;j<8;j++)
{
vtot=0;
printf("\n");
for(i=0;i<8;i++)
{
vtot += a[i][j];
printf("%d\t", a[i][j]);
}
tot +=vtot;
}
if(tot == 8)
printf("Moving on to Diagonal checking");
else
printf("Vertical criterion not fulfilled %d ", tot);
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
if(a[i][j])
{
m=i;
n=j;
while(n!=0)// running the loop leftwards
{
m++;
n--;
dtot +=a[m][n];
}
printf("diagonal left total = %d", dtot);
if(dtot == 1)
{
m=i;
n=j;
while(n!=0)// running the loop rightwards
{
m++;
n++;
dtot +=a[m][n];
}
printf("diagonal right total = %d", dtot);
}
}
}
}
return 0;
}
while(n!=0)// running the loop rightwards
{
m++;
n++;
dtot +=a[m][n];
}
That seems a pretty obvious crash to me. Increasing n
and checking for n!=0
.
The loop previous to this probably also crashes because m
runs out of array index.
Put some printf
s for m
and n
in those loops. Even better: think about the array index ranges before you write your code.
The diagonal runs aren't correctly bounded. You're only checking the n index, and you're checking it the wrong direction on the rightwards span. At some point n goes out of range and does an illegal array access.
精彩评论