On 2019-02-20 21:34 +0100, Patrick Bégou wrote: > Le 19/02/2019 à 18:34, Liu Hao a écrit : > > 在 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 > > > Thanks a lot Liu, very instructive and detailed explanation. > I had really a basic understanding of this and had some trouble to > answer a student question "why does it work with and without the > &...." It might not work, as Liu said. scanf/printf always invoke undefined behavior if the argument corresponding to "%s" is not a pointer to char. It just happens to work with x86 and x86_64, and most OS, C libraries, compilers supporting them because all pointers have same presentation. In most circumstances you don't need to use unary "&" on an array. I've never seen it in "real" software code. The stupid textbook provided by my university even claimed "you can't use unary & on an array". That kind of bulls**t made me throw it away and buy a TCPL insteadly. But, OTOH, this also stopped some newbies to misuse unary &. Maybe a good thing :(. -- Xi Ruoyao <xry111@xxxxxxxxxxxxxxxx> School of Aerospace Science and Technology, Xidian University