c - Segmentation fault error for a matrix assignment -
this code creation of grid similar of game "mines":
#include <stdio.h> #include <stdlib.h> int main(){ int nr, nc, ** mtx, i, j; //matrix costruction file * instr; instr = fopen("brasa.dat","r"); if(instr == null){ printf("\nproblem while opening file.\n"); return 1; } fscanf(instr, "%d%d", &nr, &nc); mtx = (int**) malloc(nr * sizeof(int*)); if(mtx == null){ printf("\nmemory allocation error.\n"); return 1; } else{ for(i = 0; < nr; i++) mtx[i] = (int*) malloc(nc * sizeof(int)); if(mtx[i] == null){ printf("\nmemory allocation error.\n"); return 1; } } //filling matrix for(i = 0; < nr; i++){ for(j = 0; j < nc; j++) mtx[i][j] = 0; } while(!feof(instr)){ fscanf(instr,"%d %d",&i,&j); mtx[i][j] = 9; } fclose(instr); for(i = 0; < nr; i++){ for(j = 0; j < nc; j++){ if(i == 0){ if(j == 0){ if(mtx[i][j+1] > 8) mtx[i][j]++; else if(mtx[i+1][j] > 8) mtx[i][j]++; else if(mtx[i+1][j+1] > 8) mtx[i][j]++; } else if(j == nc-1){ if(mtx[i][j-1] > 8) mtx[i][j]++; else if(mtx[i+1][j-1] > 8) mtx[i][j]++; else if(mtx[i+1][j] > 8) mtx[i][j]++; } else{ if(mtx[i][j-1] > 8) mtx[i][j]++; else if(mtx[i][j+1] > 8) mtx[i][j]++; else if(mtx[i+1][j-1] > 8) mtx[i][j]++; else if(mtx[i+1][j] > 8) mtx[i][j]++; else if(mtx[i+1][j+1] > 8) mtx[i][j]++; } } else if(i == nr-1){ if(j == 0){ if(mtx[i+1][j] > 8) mtx[i][j]++; else if(mtx[i+1][j+1] > 8) mtx[i][j]++; else if(mtx[i][j+1] > 8) mtx[i][j]++; } else if(j == nc-1){ if(mtx[i][j-1] > 8) mtx[i][j]++; else if(mtx[i+1][j-1] > 8) mtx[i][j]++; else if(mtx[i+1][j] > 8) mtx[i][j]++; } else{ if(mtx[i][j-1] > 8) mtx[i][j]++; else if(mtx[i+1][j-1] > 8) mtx[i][j]++; else if(mtx[i+1][j] > 8) mtx[i][j]++; else if(mtx[i+1][j+1] > 8) mtx[i][j]++; else if(mtx[i][j+1] > 8) mtx[i][j]++; } } else if(j == 0){ if(mtx[i+1][j] > 8) mtx[i][j]++; else if(mtx[i+1][j+1] > 8) mtx[i][j]++; else if(mtx[i][j+1] > 8) mtx[i][j]++; else if(mtx[i-1][j+1] > 8) mtx[i][j]++; else if(mtx[i-1][j] > 8) mtx[i][j]++; } else if(j == nc-1){ if(mtx[i+1][j] > 8) mtx[i][j]++; else if(mtx[i+1][j-1] > 8) mtx[i][j]++; else if(mtx[i][j-1] > 8) mtx[i][j]++; else if(mtx[i-1][j-1] > 8) mtx[i][j]++; else if(mtx[i-1][j] > 8) mtx[i][j]++; } else{ if(mtx[i-1][j-1] > 8) mtx[i][j]++; else if(mtx[i][j-1] > 8) mtx[i][j]++; else if(mtx[i+1][j-1] > 8) mtx[i][j]++; else if(mtx[i+1][j] > 8) mtx[i][j]++; else if(mtx[i+1][j+1] > 8) mtx[i][j]++; else if(mtx[i][j+1] > 8) mtx[i][j]++; else if(mtx[i-1][j+1] > 8) mtx[i][j]++; else if(mtx[i-1][j] > 8) mtx[i][j]++; } if(mtx[i][j] > 8) printf("*\t"); else printf("%d\t", mtx[i][j]); } } free(mtx); return 0; }
during execution of program appears segmentation fault. doing several tests noticed problem should between line 85 , line 158. can me?
you have invalid access
// ... else if(i == nr-1){ // nr - 1 if(j == 0){ // ... } else if(j == nc-1){ // ... else if(mtx[i+1][j] > 8) // + 1 nr (invalid access) // ...
Comments
Post a Comment