Can it cause problems to pass the address to an array instead of the array?

Yes, the code is undefined behaviour. The argument corresponding to %s must have the type char *. This is described in C17 7.21.6.2/12 under the s specifier:

[...] the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically.

which says fairly clearly that the pointer should have pointer-to-character type, and not point to the whole array.

Undefined behaviour means that anything can happen. It might behave as if you omitted the &, or it might format your hard drive.

Given that it is extremely easy to avoid undefined behaviour in this case, I don't really see any reason to engage in arguments about whether it is OK to rely on the behaviour of undefined behaviour in this situation.


Using &str instead of str didn't cause any problems in this case because the addresses of those two are the same. See this past question for an explanation. But as you note, the type of &str is different, and the compiler throws up a warning, and the actual behavior will depend on architecture and implementation.

Tags:

C

Arrays