简体   繁体   中英

Using 'scanf', what is the difference between having a variable or pointer in the second argument?

What is the difference between having a variable or pointer in the second argument of scanf .

For example:

scanf("%f",&r);

vs

scanf("%f",r);

When you pass a value to any function, that value gets copied prior to the function call. The function uses the copy, and that copy is then discarded when the function returns.

scanf needs to put its results somewhere you can get them back after the function has returned. Thus, you don't give it any disposable copies of anything. Instead, you tell where the things live, so that it can store the user's input right there. That's a pointer. In short : you always pass a pointer to scanf .

However, depending on the value's type, pointers will show with a different notation. That is, if you're scanning for an integer i , for instance, of type int , you'll have to take i 's address (= transform into a pointer) by adding an amperstand in front of it : scanf("%d",&i); . Whereas if you're scanning for a string s , its type is char* , which is already a pointer to a buffer of characters (take note of the trailing star in the type). The adress of the buffer is what scanf expects, and therefore there's no need to dereference : scanf("%s",s); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM