Two dimensional arrays and pointers

后端 未结 4 1330
春和景丽
春和景丽 2021-01-18 04:23

I have the following code snippet:

char board[3][3] = {
                     {\'1\',\'2\',\'3\'},
                     {\'4\',\'5\',\'6\'},
                          


        
4条回答
  •  长发绾君心
    2021-01-18 04:46

    As per my knowledge, board (i.e) array name represents the address of the first subarray (i.e) board[0]

    This is only true if board is used outside of these contexts

    • As operand of the & operator
    • As operand of sizeof

    When any of that applies, expression board represents the array and keeps having the type of the array (char[3][3]). Applying the & operator to it results in getting the address of the array, which of course equals the address of its first element, merely having a different type (char(*)[3][3] instead of char(*)[3]). The same that is true about the array board is true about its first sub array board[0].

    When you use it outside of those contexts, you get the address of the first element (subarray in your case). That address is not an object but just a value. Value have no address, but objects have. Trying to apply & on it would fail. For example

    // error: trying to apply '&' on something that has no address
    &(1 ? board : board)
    

    Note that anything said above applies to C; not necessarily to C++.

提交回复
热议问题