Why don't we use & in scanf while storing string in C? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why don't we use & in scanf while storing string in C?

Say eg. char c[10]; scanf("%s",c); Why don't we use &c here?

15th Jul 2021, 4:17 PM
Srinath
5 Answers
+ 3
because 'c', when used without an index as it is, is considered a pointer (or simply the array's starting place in memory) to the first value in the array. when you use for instance, &<a variable with a single peice of data (ex. int n; scanf("%d", &n;))> you are really accessing the memory location of that variable. So, in short, you dont use the & before 'c' in this case because 'c' is ALREADY a pointer (memory address)
15th Jul 2021, 4:35 PM
Slick
Slick - avatar
+ 3
In case of a string (character array), the variable itself points to the first element of the array in question. Thus, there is no need to use the '&' operator to pass the address. '&' is used to get the address of the variable. src:- https://www.google.com/amp/s/www.geeksforgeeks.org/not-used-strings-scanf-function/amp/ Any example code to what @Slick and I mentioned. https://code.sololearn.com/cc6e9RnbX38D/?ref=app
15th Jul 2021, 4:35 PM
Rohit
+ 1
Rohit but why do I get error when I type printf("%c", name) removing the * in name. By your definition, as char points to the first element in the array, why isn't 's' in 'sololearn' getting displayed separately? Isn't char supposed to just get one character and leave the rest, in this case 's' and leaving 'ololearn'? Why this works only if I use printf("%c", *name)? or printf("%s", name) as it gets displayed as a string
16th Jul 2021, 8:00 AM
Srinath
+ 1
Verstappen name is an array of characters which means its a "string", so you will need to do for it to be valid. printf("%s", name); %s is for string (or array of characters). %c is for a single character. *name = name[0] *(name + 1) = name[1] And we know both are a single character and hence this works printf("%c", *name); displaying the name[0] which is "s" in our example.
16th Jul 2021, 8:09 AM
Rohit
0
Rohit ohh okie got it thanks
16th Jul 2021, 12:08 PM
Srinath