Runtime error in the following code

后端 未结 4 2035
北恋
北恋 2021-01-26 10:13

The following code,according to me should run successfully,but fails at runtime.I don\'t get the reason:

 void main()
 {
   int arr[5][3]={1,2,3,4,5,6,7,8,9,10,1         


        
4条回答
  •  一整个雨季
    2021-01-26 11:08

    An array of arrays and a pointer to a pointer is quite different, and can't be used interchangeably.

    For example, if you look at your array arr it looks like this in memory

    +-----------+-----------+-----------+-----------+-----+-----------+
    | arr[0][0] | arr[0][1] | arr[0][2] | arr[1][0] | ... | arr[4][2] |
    +-----------+-----------+-----------+-----------+-----+-----------+
    

    When you have the pointer-to-pointer p the program don't really knows that it points to an array of arrays, instead it's treated as an array of pointers, which looks like this in memory:

    +------+------+------+-----+
    | p[0] | p[1] | p[2] | ... |
    +------+------+------+-----+
      |      |      |
      |      |      v
      |      |      something
      |      v
      |      something
      v
      something
    

    So when you do p + 1 you get to p[1] which is clearly not the same as arr[1].

提交回复
热议问题