简体   繁体   English

指向C中的2D数组的指针

[英]Pointer to 2D array in C

I am trying to make a sudoku solver in C. I have tried to make a function to solve the sudoku and then return the grid. 我试图在C中创建一个数独求解器。我试图创建一个函数来解决数独,然后返回网格。

void solve(int *grid){
    //solve sudoku
}

int main(){
    int[][] grid = {
        {5,3,0,0,7,0,0,0,0},
        {6,0,0,1,9,5,0,0,0},
        {0,9,8,0,0,0,0,6,0},
        {8,0,0,0,6,0,0,0,3},
        {4,0,0,8,0,3,0,0,1},
        {7,0,0,0,2,0,0,0,6},
        {0,6,0,0,0,0,2,8,0},
        {0,0,0,4,1,9,0,0,5},
        {0,0,0,0,8,0,0,7,9}
    };
solve(&grid);
}

This does not seem to work. 这似乎不起作用。 It needs to take a pointer because it should edit the array not a copy Why is this? 它需要一个指针,因为它应该编辑数组而不是副本。为什么?

First of all this declaration of an array 首先,此数组声明

int[][] grid = {
    {5,3,0,0,7,0,0,0,0},
    {6,0,0,1,9,5,0,0,0},
    {0,9,8,0,0,0,0,6,0},
    {8,0,0,0,6,0,0,0,3},
    {4,0,0,8,0,3,0,0,1},
    {7,0,0,0,2,0,0,0,6},
    {0,6,0,0,0,0,2,8,0},
    {0,0,0,4,1,9,0,0,5},
    {0,0,0,0,8,0,0,7,9}
};

is wrong. 是错的。 You have to use square brakets after the identifier and specify at least the number of elements in the inner dimension. 您必须在标识符后使用方括号,并至少指定内部尺寸中的元素数量。

#define N 9

//...
int grid[][N]  = {
    {5,3,0,0,7,0,0,0,0},
    {6,0,0,1,9,5,0,0,0},
    {0,9,8,0,0,0,0,6,0},
    {8,0,0,0,6,0,0,0,3},
    {4,0,0,8,0,3,0,0,1},
    {7,0,0,0,2,0,0,0,6},
    {0,6,0,0,0,0,2,8,0},
    {0,0,0,4,1,9,0,0,5},
    {0,0,0,0,8,0,0,7,9}
};

If you want to pass the array to a function then the function can be declared like 如果您想将数组传递给函数,则可以将函数声明为

void solve( int ( *grid )[N], size_t n );

and called like 叫像

solve( grid, N );

Take into account that arrays do not have the copy assignment operator and you may not assign an array identifier with a pointer. 请注意,数组没有复制分配运算符,并且可能无法使用指针分配数组标识符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM