[英]Using a 2-dimensional array, segmentation fault (core dumped)
我在不同的网站上浏览..但是任何使我明白问题出在什么地方..我刚刚开始用C编程。任务是使用2维数组绘制棋盘,并构建一个黑白交替的函数(使用适当的符号) )。
#include <stdio.h>
char makeChessBoard(int length,int width, char board[width][length]) {
int i;
int j;
for (i = 0; i < width; i++) {
// printf("\n");
for (j = 0; j < length; j++) {
if((i+j)%2 == 0)
board[i][j] = "[#]";
else
board[i][j] = "[ ]";
}//for
}//for
//return 0;
}//makeChessBoard
int main()
{
int x = 9;
int y = 9;
char initialBoard[x][y];
char chessBoard[x][y];
makeChessBoard(initialBoard[x][y],x,y);
for (int i = 0; i < x; i++) {
printf("\n");
for (int j = 0; j < y; j++) {
printf("%s", chessBoard[i][j]);
}//for
}//for
}//main
开启警告
makeChessBoard(initialBoard[x][y],x,y);
应该
makeChessBoard(x, y, initialBoard);
board[i][j] = "[#]"; /* you can't assign a string, use a char e.g: '#' */
一样
board[i][j] = "[ ]";
最后,您要打印字符,请使用:
printf("%c", chessBoard[i][j]);
代替
printf("%s", chessBoard[i][j]);
您可以这样调用makeChessboard
:
makeChessBoard(initialBoard[x][y],x,y);
但是它是这样定义的:
char makeChessBoard(int length,int width, char board[width][length])
请注意,您在错误的参数位置传递了数组。
此外,您要传递特定的数组元素(x,y),而不是整个数组。
尝试在启用警告的情况下运行代码(gcc -Wall ...),然后检查编译器将告诉您什么。 segfault的直接原因可能是char而不是char *。
1)您调用函数makeChessBoard(initialBoard[x][y],x,y);
和函数定义不同,它应该是: (int length,int width, char board[width][length])
。
2)在功能makeChessBoard更换board[i][j] = "[#]";
board[i][j] = '#';
。 同样,更改board[i][j] = "[ ]";
board[i][j] = ' ';
。
3)在打印时,应在此二维数组中填充值, initialBoard
打印initialBoard
的值,因此更改printf("%s", chessBoard[i][j]);
到printf("[%c]", initialBoard[i][j]);
。
4)数组索引从零开始,因此如果要打印国际象棋棋盘, x
和y
应该设置为8
。
#include <stdio.h>
char makeChessBoard(int length,int width, char board[width][length])
{
int i;
int j;
for (i = 0; i < width; i++)
{
for (j = 0; j < length; j++)
{
if( ((i+j) % 2) == 0)
board[i][j] = '#';
else
board[i][j] = ' ';
}//for
}//for
}//makeChessBoard
int main()
{
int x = 8;
int y = 8;
int i,j;
char initialBoard[x][y];
//char chessBoard[x][y]; /* You are not using this 2-D array */
makeChessBoard(x,y,initialBoard);
for (i = 0; i < x; i++)
{
for (j = 0; j < y; j++)
{
printf("[%c]", initialBoard[i][j]);
}//for
printf("\n");
}//for
}//main
输出 :
[#][ ][#][ ][#][ ][#][ ]
[ ][#][ ][#][ ][#][ ][#]
[#][ ][#][ ][#][ ][#][ ]
[ ][#][ ][#][ ][#][ ][#]
[#][ ][#][ ][#][ ][#][ ]
[ ][#][ ][#][ ][#][ ][#]
[#][ ][#][ ][#][ ][#][ ]
[ ][#][ ][#][ ][#][ ][#]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.