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
Whe开发者_Go百科n 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.
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.
In the function declaration use have char arr[ROWS][COLS]
and in your loop you use arr
as arr[i][j]
, where i
is used to loop till COLS
and j
is used to loop till ROWS
.
Your COLS
and ROWS
are swapped between both situations.
You swapped ROWS and COLS around in the loop.
The expression arr[i][j]
is equivalent to *(&arr[0][0] + COLS*i + j)
, and because of the swap-around, the last access becomes *(&arr[0][0] + COLS*(COLS - 1) + (ROWS - 1))
.
If, e.g., COLS
is 100 and ROWS
is 50, then the last element accessed will be 100*99+49 = 9949 bytes from the start, but the array is only 5000 bytes. Flipping things the right way around, and the last access becomes 100*49+99 = 4999, which is the last byte of the array.
精彩评论