casting void** to 2D array of int - C

前端 未结 1 1802
夕颜
夕颜 2020-11-22 00:07

i am trying to cast a void** pointer to an int** 2D array in C

here is the code that i am trying to work with (with all the extraneous bits removed):



        
1条回答
  •  无人共我
    2020-11-22 01:00

    The compiler is right, an array of arrays (or a pointer to an array) is not the same as a pointer to a pointer. Just think about how they would be laid out in memory:

    A matrix of size MxN in the form of an array of arrays:

    +--------------+--------------+-----+----------------+--------------+-----+------------------+
    | matrix[0][0] | matrix[0][1] | ... | matrix[0][N-1] | matrix[1][0] | ... | matrix[M-1][N-1] |
    +--------------+--------------+-----+----------------+--------------+-----+------------------+
    

    A and the same "matrix" in the form of pointer to pointer:

    +-----------+-----------+-----------+-----+
    | matrix[0] | matrix[1] | matrix[2] | ... |
    +-----------+-----------+-----------+-----+
      |           |           |
      |           |           V
      |           |           +--------------+--------------+-----+
      |           |           | matrix[2][0] | matrix[2][1] | ... |
      |           |           +--------------+--------------+-----+
      |           |
      |           V
      |           +--------------+--------------+-----+
      |           | matrix[1][0] | matrix[1][1] | ... |
      |           +--------------+--------------+-----+
      |
      V
      +--------------+--------------+-----+
      | matrix[0][0] | matrix[0][1] | ... |
      +--------------+--------------+-----+
    

    It doesn't matter if you allocate the correct size, the two variables simply are incompatible which is what your compiler is telling you.

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