c++ dynamic array initialization with declaration

后端 未结 4 839
广开言路
广开言路 2020-12-03 09:12

I have function like this:

void findScarf1(bool ** matrix, int m, int n, int radius, int connectivity); 

and in main funct

4条回答
  •  清歌不尽
    2020-12-03 09:28

    If you look at how your array is laid out in memory, and compare it how a pointer-to-pointer "matrix" is laid out, you will understand why you can't pass the matrix as a pointer to pointer.

    You matrix is like this:

    [ matrix[0][0] | matrix[0][1] | ... | matrix[0][6] | matrix[1][0] | matrix[1][1] | ... ]
    

    A matrix in pointer-to-pointer is like this:

    [ matrix[0] | matrix[1] | ... ]
      |           |
      |           v
      |           [ matrix[1][0] | matrix[1][1] | ... ]
      v
      [ matrix[0][0] | matrix[0][1] | ... ]
    

    You can solve this by changing the function argument:

    bool (*matrix)[7]
    

    That makes the argument matrix a pointer to an array, which will work.


    And by the way, the matrix variable you have is not dynamic, it's fully declared and initialized by the compiler, there's nothing dynamic about it.

提交回复
热议问题