简体   繁体   中英

Segmentation fault while updating an 2D array

I'm working on 2D arrays and pointers and I'm trying to create a crossword puzzle. I'm a newbie on C so still confused about pointer and arrays. In this code I'm trying to insert words from struct array to 2D array. When I'm debugging my code inserts(I hope it does) 2 words to the array but in the 3rd one I get segmentation fault.

My struct:

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;

What I'm trying to do is reading the direction of the word and insert the appropriate place on my 2D array. Likely:

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

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

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

My function to insert strings to the board:

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;
}

regarding:

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;

and

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

the field: word is a pointer. That pointer has not been set to point to some memory that the application owns (via malloc() or calloc() )

So the application is writing where ever the trash in the field word happens to point. This is undefined behavior and can lead to a seg fault event.

What is the actual definition of `myBoard[][]?

what are the value(s) in the instance of Word_t nWord[ source ] when the failure occurs?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM