I'm trying to make a program in C that generates a random sudoku. It generates random number and checks if in the row or in the col or in the square 3x3 there is the same number, if not it puts it in the cell e goes to the next. The only problem is with row 5, when the index is 6 it gives Segmentation Fault. If I change as I comment in the program, it goes in loop. What is wrong?
include <string.h>
#include <stdlib.h>
#include "sudoku.h"
#include <stdio.h>
#include <time.h>
int dimension = 9;
int main(int argc, char** argv){
int dimension = 9;
int j ,k ;
int ** sudo = malloc(sizeof(*sudo)*dimension);
for ( j = 0; j< dimension; j++){
sudo[j] = malloc(sizeof(int)*dimension);
for ( k = 0; k<dimension; k++){
sudo[j][k] =0;
}
}
riempiSudoku(sudo);
return 0;
}
void riempiSudoku(int** sudo){ //fill sudoku
int i,j;
srand ( time(NULL));
srand(rand());
for (i=0;i<dimension;i++){
for(j=0;j<dimension;j++){
int ran;
do
ran= rand() %9 ;
while(checkSquare(sudo,i,j,ran+1)||checkRow(sudo,i,ran+1)
||checkCol(sudo,j,ran+1));
sudo[i][j] = ran+1;
printf("%d", sudo[i][j]);
}
printf("\n");
}
}
int checkRow(int** sudo, int row, int value){ //check if the number is in the row
int i;
for (i = 0; i<dimension; i++){
if (sudo[row][i] == value)
return 1;
}
return 0;
}
int checkCol(int** sudo, int col, int value){//check if the number is in the col
int i;
for (i = 0; i<dimension; i++){
if (sudo[i][col] == value)
return 1;
}
return 0;
}
int checkSquare(int** sudo, int row, int col, int value){ //check if the number is in the square 3x3
int i,j;
if (row==0||row==2||row==1){
if(col==0||col==1||col==2){
for(i=0;i<3;i++){
for(j=0;j<3;j++){
if (sudo[i][j] == value)
return 1;
}
}
return 0;
}
if(col==3||col==4||col==5){
for(i=0;i<3;i++){
for(j=3;j<6;j++){
if (sudo[i][j] == value)
return 1;
}
}
return 0;
}
if(col==6||col==7||col==8){
for(i=0;i<3;i++){
for(j=6;j<9;j++){
if (sudo[i][j] == value)
return 1;
}
}
return 0;
}
}
if (row==3||row==4||row==5){
if(col==0||col==1||col==2){
for(i=3;i<6;i++){
for(j=0;j<3;j++){
if (sudo[i][j] == value)
return 1;
}
}
return 0;
}
if(col==3||col==4||col==5){
for(i=3;i<6;i++){
for(j=3;j<6;j++){
if (sudo[i][j] == value)
return 1;
}
}
return 0;
}
if(col==6||col==7||col==8){
for(i=3;i<6;i++){
for(j=6;j<9;j++){
if (sudo[i][j] == value)
return 1;
}
}
return 0;
}
}
if (row==6||row==7||row==8){
if(col==0||col==1||col==2){
for(i=6;i<9;i++){
for(j=0;j<3;j++){
if (sudo[i][j] == value)
return 1;
}
}
return 0;
}
if(col==3||col==4||col==5){
for(i=6;i<9;i++){
for(j=3;j<6;j++){
if (sudo[i][j] == value)
return 1;
}
}
return 0;
}
if(col==6||col==7||col==8){
for(i=6;i<9;i++){
for(j=6;j<9;j++){
if (sudo[i][j] == value)
return 1;
}
}
return 0;
}
}
}