about the expression “&anArray” in c

后端 未结 3 1784
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:46

    The printf format %s means “The corresponding argument is a pointer to char. Print the string at that location.” And a string, for this purpose, is a sequence of characters ending in a null character.

    When you passed &ar to printf, you passed the address of the 'a' (although the type is wrong; printf expects a pointer-to-char, and you passed a pointer-to-array-of-char, but they have the same address), and printf saw the string 'a', 'b', 'c', '\0', so it printed "abc". The same would have happened if you passed ar or &ar[0]; those evaluate to the same address.

    When you passed &ar[1] to printf, you passed a pointer to where the 'b' is, and printf saw the string 'b', 'c', '\0', so it printed "bc".

    If you want to pass just the single character at a location, use the %c format and pass a character (instead of a pointer to character). For example, if you use the %c format with *ar, 'a' will be printed, and, if you use %c with *&ar[1], 'b' will be printed.

    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 first element if I am not mistaken.

    When used in an expression, ar acts as a pointer to the first element of the array, the same as &ar[0]. &ar and ar are the same address (the first character in the array is at the same address as the start of the array) although they have different types (pointer to array of char and pointer to char).

    the output for %c isn't even a character

    It is a character, just not what you were expecting and perhaps not a normal character or a printable character. %c expect to be passed a character argument, but you passed it an address argument.

    If so, how does the compiler verify that the identifier following "&" is in reference to an array, does it actually search for it in a list of arrays so for declared?

    The parsing is more complicated than that (essentially, the identifier is identified as a known array before the & is considered, then the combined expression of the & and the identifier is evaluated). However, the effect is that &ar evaluates to the same address as the first element.

提交回复
热议问题