Is an ampersand before a char array affect scanf? It is legal?

When we usually enter a string, we do this:

#include <stdio.h> int main() { char str[256]; scanf("%s",str); //Other Operation } 

But today, in a programming class, one of my friends wrote a scanf line as follows:

 scanf("%s",&str); 

and it passes the compilation and it works.

The question is, do I want to know if this is "legal" in C or not, or just undefined behavior?

+7
c string arrays scanf
source share
3 answers

This behavior is undefined (because type scanf() expects char * , but you pass char (*)[256] ), but it usually "works" (seems to work), since the address of the array is often the same (relative to the numeric value of the pointer ) as the address of its first element.

From the official documentation:

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

(my accent)

+6
source share

This is technically undefined behavior. However, both methods work in practice with char arrays, because the reference to str passed to scanf() turns into a pointer to the first element, which will be equal to * a pointer to the array itself (address str or &str ), therefore the same value transmitted anyway.

I'm not sure if you have worked with strings so far, but keep in mind that if you look at what is not an array, it’s easier to say that your friend method would be correct:

 int myInt; scanf("%d", &myInt); 

scanf() looking for a pointer, so you want to tell it the address of an integer variable. This is because passing myInt gives it a value (currently garbage), while &myInt tells where to put the value that it reads.

* Except Win16.

+2
source share

Both str and &str defined to take the value of the memory address of the first element of the array. Although H2CO3 indicates that this behavior is undefined, this will always work in practice.

0
source share

All Articles