我正在研究二维数组和指针,并且正在尝试创建一个填字游戏。我是 C 新手,所以仍然对指针和数组感到困惑。在此代码中,我尝试将单词从结构数组插入到二维数组。当我调试代码时,我会向数组插入(我希望如此)2 个单词,但在第三个单词中出现段错误。
我的结构:
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;
我想做的是读取单词的方向并在二维数组上插入适当的位置。可能:
*****
*****
***** //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 ]
实例中的值是什么?
关于c - 更新二维数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49786914/