+ 2
why is "&" used in scanf and not in getchar or gets [SOLVED]
why is "&" used in scanf and not in getchar or gets even though they're all assigning a value to a variable? eg: char n[10]; gets(n); versus char n; scanf("%c", &n);
9 Antworten
+ 1
in scanf, you need to tell where to save input value. But getchar() , getc() accept input and destination is lvalue to choose.
scanf("%d", &n) ; // store input at address of variable n.
char ch = getchar() ; accept input and assign it into ch. Explicitly we mentioning destination..
+ 1
Jayakrishna🇮🇳
i need a little elaboration . what about a case like this?:
char n[10];
gets(n);
if n is the value and &n is the address why aren't we using &n to send the input to the address?
+ 1
gets() accept only stream of character.
So your n[] is an array.
Arrays don't need to specify address, it is automatically points to first location of array.. You can see that scanf also don't need to specify & for stream of characters, ( for string)
Like
scanf("%s", n) ;
gets() don't work for int, double, or any other..
+ 1
Jayakrishna🇮🇳
so would you need a & to point to a int array or this applies to any kind of array?
+ 1
You can't input array elements into int array directly like a character array or string.. So you point to individual locations of int array. So you need &. But all arrays
For ex: int arr[10];
arr points to first location, and &arr points to same first location. But difference is &arr referes entire array where arr points to the only first element. character array is continues locations for storing characters and need single byte for a character. so for next character, it automatically points to next byte. but integer requires 2 or 4 bytes..
chat ch[10] ;
scanf("%s", ch) ; // fine, value to entire array..
int arr[10];
scanf("%d", &arr[0] ) ; // won't possible to add entire array elements..
Hope it helps....
+ 1
Jayakrishna🇮🇳
got it, thank you .
+ 1
That differs depending on whether you want to get a character or a character chain.
Note that by adding a '&' before a variable's identifier, you're referring to the address not the value...
That's why in scanf you used &n. Because you're trying to pass a pointer to n.
Unlike the first case when you passed n without the '&', in this case you're already passing an address to a character (which is the first element in the string n).
To learn more about this you need to know what are strings in c.
I recommend reading more about these topics:
- Pointers.
- Memory.
- Characters and Strings
- The difference between Arrays, Pointers, and Strings.
0
You're welcome..
0
scanf is a formatted function can take any type of variable as a parameter
gets is an unformatted function used only for string input
In both of the cases string input doesnt require & opreator
Since string is an array of characters terminated by ‘\0’
Array can represents its starting address