[英]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.