Why does scanf function use '& ',but when we use array string scanf does not use '&'. | SoloLearn: Learn to code for FREE!


Why does scanf function use '& ',but when we use array string scanf does not use '&'.


11/14/2019 3:57:42 AM

Ankit Chaturvedi

8 Answers

New Answer


& means at address, so when you say- int x; scanf("%d",&x); The above line means that what ever value you are giving, store it at the address of x. But when you write- int arr[5]; for(int i=0; i<5; i++){ scanf ("%d",arr[i]); } The above code doesn't need an & because the array name contains the base address of the array which means the first entered value will directly go to the base address which is also the same address location of the first element at the index arr[0].


I saw this exact question was asked here before. First you need to know what an array in c is. Array is a continuous block of memory. Take this example. char a[3]; In memory this looks like a[0] a[1] a[2] 0x8b000 0x8b001 0x8b002 So if you know the staring address and you know the size(or element count in array * size of single element 3 * 1 in this case) you can define an array. Array in c is a pointer. In other words it's an address. Address of the staring element. As you can see you're still passing an address into the scanf when passing an array.


We always want to pass in an address into scanf. As scanf wants to modify that value. & gets the address of an variable. Int b; &b is the address of b.


Why do we use '&' in other case


#include <stdio.h> int main() {int a[3]={1,2,3}; printf("%d",a); return 0; } How can i fix this?


include <stdio.h> int main() { int a[3]; int i; for(i=0;i<3;i++) { scanf("%d",&a[i]); }printf("%d",a[1]); return 0; } it is giving me no error


Ankit Chaturvedi Your code works. What do you expect it to ouput? When you enter 3 numbers as input it will output the 2nd number you entered. #include <stdio.h> int main() {     int a[3];     int i;     for(i=0;i<3;i++)     {         scanf("%d", &a[i]);     }     printf("%d", a[1]);     return 0; } Here you can try it. https://code.sololearn.com/cI12ynatoa95/?ref=app Sample input : 1 2 3 Sample output : 2


I mean that,use with & giving me no error ,but it should give an error