2

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;
}
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
Jude
  • 449
  • 1
  • 7
  • 17
  • Do you have access to a debugger (maybe gdb, lldb, etc..)? Try running a backtrace and posting what pops up here so we have more information. – Yashwanth Sep 02 '15 at 21:42
  • change to `int (*sudoArr)[SIZE]; sudoArr = malloc(sizeof(*sudoArr) * SIZE );` or `int (*sudoArr)[SIZE] = malloc(sizeof(int) * SIZE * SIZE);` – BLUEPIXY Sep 02 '15 at 21:45
  • For this code it's silly to do dynamic allocation at all. Since the array dimensions are statically known, and it is used only inside the function where it is declared, `int sudoArr[SIZE][SIZE];` (and no `malloc()`) would be better. If it needed to be shared among functions then it could be declared that way as a global, or it could be declared that way in `main()` and passed as an argument to the other functions. – John Bollinger Sep 02 '15 at 22:14
  • @JohnBollinger I see, I was just trying to practice dyn arrays but I guess I'll try a fixed array. – Jude Sep 02 '15 at 22:16

1 Answers1

1

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

Denis Babarykin
  • 805
  • 1
  • 6
  • 12