Re: [OT] basic detail

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



在 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, 7.21.6.2 The fscanf function, 12
[3] http://c-faq.com/null/machexamp.html

-- 
Best regards,
LH_Mouse




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux