about the expression “&anArray” in c

后端 未结 3 1761
Happy的楠姐
Happy的楠姐 2021-01-16 18:18

First, I read that:

  • array
  • &array
  • &array[0]

will all be the same as long as \"ar

3条回答
  •  野的像风
    2021-01-16 18:39

    Seems that &ar is taken as a pointer to the first element instead of a pointer to "ar", which itself is a pointer to the pointer of the first element if I am not mistaken.

    You are mistaken. &ar is a pointer to the array ar, but the array ar is not a pointer of any sort (it's an array), so &ar is not a pointer to a pointer.

    An array is a contiguous sequence of objects - in the case of ar, it's a contiguous set of 4 chars. &ar is a pointer to this set of 4 chars, which necessarily means it points at the same place as &ar[0], a pointer to the first char in that set. It has a different type, though: &ar has type char (*)[4] which means "pointer to array of 4 chars" and &ar[0] has type char *, which means "pointer to char".

    The confusion arises because in almost all expressions, ar evaluates to a pointer to the first element of the array (the exceptions to this are when it's the operand of the unary & operator or the sizeof operator). This doesn't mean that ar is a pointer though - it's not - just that in most cases it evaluates to a pointer value.

提交回复
热议问题