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?
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)
It is technically undefined behaviour. However, both methods work in practice with char arrays because the reference to str
being passed to scanf()
turns into a pointer to the first element, which will be equal* to a pointer to the array itself (the address of str
, 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:
int myInt;
scanf("%d", &myInt);
scanf()
is looking for a pointer, so you want to give it the address of your integer variable. This is because passing myInt
gives it a value (currently garbage), whereas &myInt
tells it where to put the value that it reads.
*Except on Win16.
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.