+ 1

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

14th Nov 2019, 3:57 AM
Ankit Chaturvedi
Ankit Chaturvedi - avatar
9 Antworten
+ 9
& 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].
14th Nov 2019, 4:31 AM
Avinesh
Avinesh - avatar
+ 5
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.
14th Nov 2019, 4:27 AM
__IAS__
__IAS__ - avatar
+ 3
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.
14th Nov 2019, 4:31 AM
__IAS__
__IAS__ - avatar
0
Why do we use '&' in other case
14th Nov 2019, 4:30 AM
Ankit Chaturvedi
Ankit Chaturvedi - avatar
0
#include <stdio.h> int main() {int a[3]={1,2,3}; printf("%d",a); return 0; } How can i fix this?
14th Nov 2019, 4:46 AM
Ankit Chaturvedi
Ankit Chaturvedi - avatar
0
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
14th Nov 2019, 5:13 AM
Ankit Chaturvedi
Ankit Chaturvedi - avatar
0
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
14th Nov 2019, 7:32 AM
__IAS__
__IAS__ - avatar
0
I mean that,use with & giving me no error ,but it should give an error
14th Nov 2019, 1:02 PM
Ankit Chaturvedi
Ankit Chaturvedi - avatar
0
Thank You for the help Avinesh __IAS__
6th Oct 2020, 3:30 PM
Constantine Xsavior