Does ampersand in front of char's array affect scanf? Is it legit?

arrays, c, scanf, string

Solution

It's undefined behavior (because the type `scanf()` expects is `char *`, but you pass in a `char (*)[256]`), but it usually "works" (appears to be working) since the address of an array is often the same (regarding the numeric value of the pointer) as the address of its first element.

From the official documentation:

If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the space provided, the behavior is undefined.

(emphasis mine)

Problem

When we usually input the string, we do this: ``` #include <stdio.h> int main() { char str[256]; scanf("%s",str); //Other Operation } ``` But, today, in programming class, one of my friends wrote `scanf` line like this: ``` scanf("%s",&str); ``` and it pass the compilation, and works. The question is, I'd like to know if this is "legal" in C or not, or just an undefined behavior?

Original source

Related problems