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?
Both
str
and&str
are defined to take the value of the memory address of the first element of the array. Notwithstanding H2CO3's indication that this is undefined behaviour, this will always work in practice.It's undefined behavior (because the type
scanf()
expects ischar *
, but you pass in achar (*)[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:
(emphasis mine)
It is technically undefined behaviour. However, both methods work in practice with char arrays because the reference to
str
being passed toscanf()
turns into a pointer to the first element, which will be equal* to a pointer to the array itself (the address ofstr
, or&str
), so the same value gets passed either way.I'm not sure whether you've only been working with strings so far, but bear in mind that if you look at something that's not an array, it's easier to tell that your friend's method would be correct:
scanf()
is looking for a pointer, so you want to give it the address of your integer variable. This is because passingmyInt
gives it a value (currently garbage), whereas&myInt
tells it where to put the value that it reads.*Except on Win16.