c++ trying to understand clockwise rules for deciphering complicated syntax

后端 未结 2 716
孤独总比滥情好
孤独总比滥情好 2021-01-07 14:13

I have the following code:

int ia[3][4] = {    //
{0, 1, 2, 3},   //
{4, 5, 6, 7},   //
{8, 9, 10, 11}  //
};

int (*p4)[4] = ia;
cout << \"(*(p4 + 0))         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-07 15:02

    I don't understand the last one how it arrives at 1.

    Undefined behavior got you there.

    Due to operator precedence (the array indexing operator binds tighter than the pointer dereference operator),

    *(p4 + 0)[3] is the same as:
    *((p4 + 0)[3]), which is the same as:
    *(p4[3]), which is the same as:
    p4[3][0].

    For your array. the valid indices for the first dimension are: 0, 1, and 2. Accessing the array using the index value of 3 accesses memory beyond valid range, leading to undefined behavior.

提交回复
热议问题