分段故障,第一次使用2D阵列

时间:2015-09-02 21:41:20

标签: c pointers multidimensional-array segmentation-fault sudoku

我第一次使用2D数组进行数独检查程序;下面是我的代码。

我的程序编译时没有错误,但是当我运行它时,它会给我一个分段错误。

我上次编码已经有一段时间了,所以我不确定我错过了什么。我以前也没必要处理过这个错误。

我的代码:

#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;
}

1 个答案:

答案 0 :(得分:1)

首先,你为错误的矩阵分配内存。正确的将是:

int** sudoArr = (int**)malloc(SIZE * sizeof(int*));

for (int index=0; index < SIZE; ++index)
{
    sudoArr[index] = (int*)malloc(SIZE * sizeof(int));
}

使用正确的代码版本链接到在线编译器:correct sources