I am working with 2D arrays for the first time for a sudoku checker program; below is my code.
My program compiles without error, but when I run it, it gives me a segmentation fault.
It has been a while since I last coded, so I am unsure what I'm missing. I've also never had to deal with this error before.
My Code:
#include <stdio.h>
#include <stdlib.h>
int sudokuCheck();
int arrayMake();
#define SIZE 9
int main(){
int sudokAmount;
printf("Please Enter the amount of solutions to solve:\n");
scanf("%d",&sudokAmount);
arrayMake();
//sudokuCheck(sudokAmount);
return 0;
}
int arrayMake(){
int j;
int i;
int** sudoArr;
sudoArr = malloc(sizeof(int*) * SIZE * SIZE);
printf("Please Enter Sudoku Solutions(By rows)\n");
for(i = 0; i < SIZE; i++){
for(j=0; j < SIZE; j++){
scanf("%d\n", &sudoArr[i][j]);
}
}
for(i = 0; i < SIZE; i++){
for(j=0; j < SIZE; j++){
printf("%d \n", sudoArr[i][j]);
}
}
return 0;
}
First of all, you allocate memory for the matrix wrong way. Correct will be:
int** sudoArr = (int**)malloc(SIZE * sizeof(int*));
for (int index=0; index < SIZE; ++index)
{
sudoArr[index] = (int*)malloc(SIZE * sizeof(int));
}
Link to online compiler with correct version of your code: correct sources
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.