Trying to access array element in loop causes segmentation fault, why?

后端 未结 2 594
温柔的废话
温柔的废话 2021-01-25 03:16

I am trying to create a two dimensional array, which has either 1 or 0 randomly assigned to each coordinate. It works just fine until it gets to the coordinates [20][3]. After t

相关标签:
2条回答
  • 2021-01-25 03:34

    C uses 0-based indexing for arrays. So, for an array defined as

    int grid [x][y]
    

    looping for

     for ( i = 0; i <= x; i++) 
       for ( j = 0; j <= y; j++)
    

    if off-by-one. (Note the <= part).

    to elaborate, for an array of dimension p, the valid indexes are 0 to p-1, inclusive.

    You should change your loop conditions as i < x and j < y to stay withing the bounds. Accessing out of bound memory causes undefined behavior.

    That said,

    • int main() should be int main(void), at least, to conform to C standards for hosted environments.
    • There is no need to make grid as VLA here. If the dimensions are already known, better approach is to use a compile-time constant (#define) to generate the array dimensions.
    0 讨论(0)
  • 2021-01-25 03:39

    You're running past the bounds of the array. That's undefined behaviour in C, and is manifesting itself as a crash.

    Change i <= x to i < x etc, or increase the grid size.

    0 讨论(0)
提交回复
热议问题