c - 段错误,第一次使用二维数组

标签 c pointers multidimensional-array segmentation-fault sudoku

我第一次使用二维数组来编写数独检查程序;下面是我的代码。

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

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

我的代码:

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

最佳答案

首先,您以错误的方式为矩阵分配内存。正确的是:

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

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

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

关于c - 段错误,第一次使用二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32363600/

相关文章:

C - 如何限制堆中的地址访问?

python - reshape numpy为滞后值添加额外维度

.net - 使用ProtoBuf-Net,如何对多维数组进行(反)序列化?

php - 从多维数组中提取值并放置在逗号分隔的字符串中

c++ - 类问题中的 CUDA 内存管理/指针

c - 返回变量

c - c中的字符串读取

c - 二维数组中的第一个元素被覆盖 - C

c - 对指针的相同两个操作的不同行为

c++ - 初始化函数指针时出现问题?