Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault when traversing array in c

I wrote this little function in c:

void initializeArray(char arr[ROWS][COLS]){
    int i,j;
    for (i=0; i<COLS; i++){
        for (j=0; j<ROWS; j++){
            arr[i][j] = ' ';
        }
    }
}

Edit: ROWS and COLS are defined in a header file

When I call it i keep getting a segmentation fault. If I traverse the array using a pointer its okay, any ideas why?

p.s. The array being passed was defined outside a function so there's no link problems.

like image 391
yotamoo Avatar asked Nov 30 '22 16:11

yotamoo


1 Answers

In your function declaration you've got ROWS as the size of the first dimension, and COLS as the size of the second dimension; but in your function body, you're looping COLS times over the first dimension, and ROWS times over the second. Depending on whether the array declaration matches the function declaration or the "implied declaration" in the code, that may be a problem.

like image 154
Ernest Friedman-Hill Avatar answered Dec 08 '22 00:12

Ernest Friedman-Hill