c - 错误 : assigning to 'int **' from incompatible type 'int [][]

标签 c arrays struct malloc

<分区>

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define SIZE 9

typedef struct 
{
    int row;
    int col;
    int** arr;  
}parameters;

// function prototypes
void* checkRow(void* in);
void* checkCol(void* in);
void* checkSect(void* in);


int main(void)
{
    // board to test
    int grid[SIZE][SIZE] = {
                    {6, 5, 3 ,1, 2, 8, 7, 9, 4},
                    {1, 7, 4, 3, 5, 9, 6, 8, 2},
                    {9, 2, 8, 4, 6, 7, 5, 3, 1},
                    {2, 8, 6, 5, 1, 4, 3, 7, 9},
                    {3, 9, 1, 7, 8, 2, 4, 5, 6},
                    {5, 4, 7, 6, 9, 3, 2, 1, 8},
                    {8, 6, 5, 2, 3, 1, 9, 4 ,7},
                    {4, 1, 2, 9, 7, 5, 8, 6, 3},
                    {7, 3, 9, 8, 4, 6, 1, 2, 5}
                 }; 

    printf("Sudoku from Khoa Vo\n");

    int i = 0;
    int j = 0;
    for (i = 0; i < SIZE; i++)
        for (j = 0; j < SIZE; j++)
        {
            printf("%d ", grid[i][j]);
            if(j == SIZE)
                printf("\n");
        }

    // paramenter for column and row threads
    parameters *data = (parameters*) malloc(sizeof(parameters));
    data->row = 0;
    data->col = 0;
    data->arr = grid;
}

我有一个错误,但我不太清楚如何修复它,语句 data->arr = grid 上有错误,错误消息表明“错误:分配给”int **' 来自不兼容的类型 'int [9][9]。我能得到一些关于如何解决这个错误的建议吗,先谢谢了。

最佳答案

如果是数独,只需更改结构定义1

typedef struct 
{
    int row;
    int col;
    int arr[9][9];  
} parameters;

因为 int **int[][] 是不兼容的类型,因为 int[][] 存储连续的整数,而 int ** 您可以存储连续的指针,但整数不是连续的,您也不应该强制转换。

用您随后可以使用的值填充arr

memcpy(data->arr, grid, sizeof(data->arr));

因为你不能给数组赋值。

此外,使用 malloc() 时要小心,如果出错,它会返回 NULL,在这种情况下,malloc() 之后的代码将导致未定义的行为。和 do not cast void * in [tag:c] .


1您也可以将其定义为指针数组,如 this comment建议。

关于c - 错误 : assigning to 'int **' from incompatible type 'int [][],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32987863/

相关文章:

c - 这个程序会在 Turbo C 中编译吗?

c - 如何在unix机器上创建c exe

c - valgrind 中大小为 1 的无效写入/读取,未找到答案

在汇编段错误中调用 C 函数

c++ - 未命名结构和 union 中的字段变量

c++ - 为什么在 Visual Studio 中某些头文件需要链接库?

arrays - 我是否正确地追踪了这一点?

c - 在 C 中递增数组的元素时,为什么必须使用++array[c - '0' ] 而不是++array[c]?

struct - Julia:如何通过修改用户提供的字段中的原始不可变结构来生成新的不可变结构?

json - 嵌套的 Go Structs,用于带有可选结构的 JSON 编码(marshal)处理