【发布时间】:2013-02-18 13:31:35
【问题描述】:
我正在尝试编写一个简单的 C++ 算法来解决数独问题。我正在尝试在不同函数之间传递地址值,但在运行时出现分段错误。 (不用说,我不是很有经验:))
代码确实设法将 a[0] 的地址传递给 main 函数,我可以使用 main 中的指针读取值。当我尝试传递地址来解决函数时,它给出了分段错误。
(也作为次要问题,我可以在 main 中正确读取值,使用 cout
#include <iostream>
using namespace std;
int * get_input();
void solve(int *);
int main()
{
int * a;
a = get_input();
//cout << *a << " " << *(a+1) << " " << *(a+2) << " " << *(a+3) << " " << *(a+4);
//for (int i = 0 ; i < 81 ; i++) {if (i%9 == 0) cout << "\n"; cout << a[i] << " ";}
solve(a);
return(0);
}
int * get_input ()
{
int a[81];
getinput:
for (int i = 0 ; i < 81 ; i++) {a[i] = 0;}
for (int i = 0 ; i < 81 ; i++) {cin >> a[i];}
print:
for (int i = 0 ; i < 81 ; i++)
{
if (i%27 == 0){cout << "\n";}
if (i%9 == 0) {cout << "\n";}
if (i%3 == 0) {cout << " " << a[i];}
if (i%3 != 0) {cout << a[i];}
}
cout << "\n\nCheck:\n1- Fix\n2- Reset\n3- Confirm\n\n";
int check = 0;
cin >> check;
if (check == 1)
{
int input[3] = {-1, -1, -1};
while (true)
{
cin >> input[0] >> input[1] >> input [2];
if (input[1] == 0) goto print;
a[(input[2]-1)+((input[1]-1)*9)] = input[0];
}
}
if (check == 2) goto getinput;
if (check == 3) return a;
}
void solve(int * a)
{
bool matrix[9][9][9];
for (int i = 0 ; i < 81 ; i++) {for (int j = 0 ; j < 9 ; j++) {matrix[(i-i%9)/9][i%9][j] = true;}}
for (int i = 0 ; i < 81 ; i++)
{
if (a[i] == 0) continue;
else
{
for (int j = 0 ; j < 9 ; i++)
{
matrix[(i-i%9)/9][j][a[i]] = false;
matrix[j][i%9][a[i]] = false;
matrix[((i-i%9)/9)-((i-i%9)/9)%3+j%3][i%9-(i%9)%3+(j-j%3)/3][a[i]] = false;
}
}
}
for (int i = 0 ; i < 9 ; i++)
{
for (int j = 0 ; j < 9 ; j++)
{
cout << matrix[i][j][1] << " ";
}
cout << "\n";
}
}
【问题讨论】:
-
在快速运行之后,我会说它是
return ainget_input。您不能返回指向堆栈变量的指针,而是使用malloc/new分配它并返回它。 -
关闭过于本地化。
-
Arrays,
goto, ... 你确定你的意思是 C++ 吗? -
它使用 C++ IO...