簡體   English   中英

使用二維數組,分段錯誤(核心已轉儲)

[英]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)數組索引從零開始,因此如果要打印國際象棋棋盤, xy應該設置為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM