c - 更新二维数组时出现段错误

标签 c pointers multidimensional-array segmentation-fault structure

我正在研究二维数组和指针,并且正在尝试创建一个填字游戏。我是 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/

相关文章:

c - 指向结构体指针的指针

python - Python中的矩阵转置

c - 是否可以将部分共享二级缓存分配给不同的内核

不能为每个元素洗牌一次

c - 如何将stdin通过管道传递给 child 并在C中执行猫

c - 如何返回指向结构数组内元素的指针?

c++ - 在 C++ 中使用指针更改字符串值

c - 如何创建一个指向其地址存储在 char 数组中的变量的指针?

java - 深拷贝3维数组

c++ - 如何从二维数组中获取行和列 C++