簡體   English   中英

更新2D陣列時出現分割錯誤

[英]Segmentation fault while updating an 2D array

我正在研究2D數組和指針,並試圖創建一個填字游戲。 我是C的新手,因此仍然對指針和數組感到困惑。 在這段代碼中,我試圖將單詞從結構數組插入2D數組。 當我調試代碼時(我希望這樣做),將2個單詞插入數組,但是在第3個中,我遇到了段錯誤。

我的結構:

typedef struct
{
 char *word;     //word and corresponding hint
 char *clues;
 int x;      //Starting x and y positions
 int y;
 char direction;     //H for horizontal, V for vertical
 int f;      //solved or not
}Word_t;

我想做的是讀取單詞的方向,並在2D數組中插入適當的位置。 可能:

*****
*****
*****  //first state of the array
*****
*****

//insert a word like "MILK whose direction is 'H' x=1 y=1"

MILK*
*****
*****
*****
*****

我在板上插入字符串的功能:

char** updateBoard(char** myBoard, Word_t *nWords, int solve)
{
if(solve!=-1)
{
    if(nWords[solve].direction=='V')
    {
        int len=strlen(nWords[solve].word);
        for(int i=0;i<=len;i++)
        {
            myBoard[nWords[solve].y][i]=nWords[solve].word[i];
        }
    }
    else if(nWords[solve].direction=='H')
    {
        int len=strlen(nWords[solve].word);
        for(int i=0;i<=len;i++)
        {
            myBoard[nWords[solve].x][i]=nWords[solve].word[i];     //segmentation fault here
        }
    }
}
else{
    if(nWords[solve].direction=='V')
    {
        int len=strlen(nWords[solve].word);
        for(int i=0;i<=len;i++)
        {
            myBoard[nWords[solve].y][i]='_';
        }
    }
    else if(nWords[solve].direction=='H')
    {
        int len=strlen(nWords[solve].word);
        for(int i=0;i<=len;i++)
        {
            myBoard[nWords[solve].x][i]='_';
        }
    }
}
return myBoard;
}

關於:

typedef struct
{
    char *word;     //word and corresponding hint
    char *clues;
    int x;      //Starting x and y positions
    int y;
    char direction;     //H for horizontal, V for vertical
    int f;      //solved or not
}Word_t;

myBoard[nWords[solve].x][i]=nWords[solve].word[i];

字段: word是一個指針。 該指針尚未設置為指向應用程序擁有的某些內存(通過malloc()calloc()

因此,應用程序正在編寫字段word的垃圾指向的任何位置。 這是未定義的行為,可能導致段故障事件。

myBoard [] []的實際定義是什么?

發生故障時, Word_t nWord[ source ]實例的值是多少?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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