gpt4 book ai didi

c - C中指向二维数组的指针

转载 作者:太空宇宙 更新时间:2023-11-04 04:32:13 25 4
gpt4 key购买 nike

我正在尝试用 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);
}

这似乎行不通。它需要一个指针,因为它应该编辑数组而不是副本这是为什么?

最佳答案

首先声明一个数组

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

错了。您必须在标识符后使用方括号,并至少指定内部维度中的元素数。

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

如果你想将数组传递给一个函数,那么这个函数可以这样声明

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

并称呼为

solve( grid, N );

请注意,数组没有复制赋值运算符,您不能使用指针分配数组标识符。

关于c - C中指向二维数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34710125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com