[OT] basic detail

Liu Hao lh_mouse@126.com
Tue Feb 19 17:34:00 GMT 2019

在 2019/2/19 23:11, Xi Ruoyao 写道:
> On 2019-02-19 15:44 +0100, Patrick Bégou wrote:
>> Hi,
>> I need a small theoritical explanation about arrays in C.
> These questions are off-topic in gcc-help.  It should go to comp.lang.c or
> somewhere.
>> I would like to know why using:
>> char A[24];
>> scanf("%s", A);  and scanf("%s", &A); does the same thing (as it is not
>> the same code).
>> I've checked that printing A or &A with "%p" prints the same address....
>> but why ?
> STFG.  The first URL Google suggested for "address of array" is exactly the
> answer of this question:
> https://stackoverflow.com/questions/2528318/how-come-an-arrays-address-is-equal-to-its-value-in-c

Converting both `A` and `&A` to `void *` will yield the same result,
because 'an array type describes a contiguously allocated nonempty set
of objects with a particular member object type, called the /element
type/' [1]. There have to be nothing else; not even padding bytes are
allowed. However, as function arguments, the former decays to `char *`
while the latter has exact `char (*)[24]`.

`%s` requires a corresponding argument be 'a pointer to the
initial element of a character array' [2], where `A` satisfies this
requirement, so it is perfectly valid there, albeit unsafe.

Passing `&A` as the argument corresponding to either `%s` for `scanf()`
or `%p` for `printf()` results in undefined behavior because `char
(*)[24]` may have a representation from `char *` [3], which GCC warns
about if `-Wpedantic` is used with `-Wformat` or `-Wall`.

[1] ISO/IEC WG14 Draft N2176, 6.2.5 Types, 20
[2] ISO/IEC WG14 Draft N2176, The fscanf function, 12
[3] http://c-faq.com/null/machexamp.html

Best regards,

More information about the Gcc-help mailing list