-2

Why do we need to specify the address of variable and not the name of variable while using scanf function for eg: scanf("%d",&a); why we use & instead we could have written like this scanf("%d",a); so why we need to use address while using scanf()?

  • 3
    Because the C standard says the `scanf` expects a ***pointer*** to storage as a parameter for each corresponding *conversion specifier* in its *format string*. [C11 Standard - 7.21.6.2 The fscanf function(p2)](http://port70.net/~nsz/c/c11/n1570.html#7.21.6.2p2) Unless you are filling an array (e.g. with `"%s"` -- which is converted to a pointer to the first element automatically), then you will need to provide the address of the variable. – David C. Rankin Mar 28 '20 at 05:58
  • 3
    In C all parameters are passed by value. That means if you pass in `a` the function will only get the value of `a`. Which is useless to the function as it needs the address of `a` to be able to store a value into `a`. `&` is exactly the address of operator. – kaylum Mar 28 '20 at 06:00
  • Does this answer your question? [Why does scanf require &?](https://stackoverflow.com/questions/10597606/why-does-scanf-require) – ad absurdum Mar 28 '20 at 15:52
  • Another potential dupe: [why-scanf-must-take-the-address-of-operator](https://stackoverflow.com/questions/3893615/why-scanf-must-take-the-address-of-operator) – ad absurdum Mar 28 '20 at 15:54

2 Answers2

1

scanf would implicitly want an address at all cases, because the variable you will have as input must be stored somewhere in the memory, and using &variable_name you are assigning a pointer addressing the variable's location.

In case of arrays/strings, you can go without using & as because the array/string passed is infact a pointer to where the first value/character is stored. (from where you can iterate over it using pointer arithmetic, for eg: +4 for int)

1

above answers and comments gives you technical reasons but in laymen terms

so your question is basically why scanf cannot take just name of variable instead of the address.

You use scanf() to put something in a variable right?

Now lets suppose you want to deliver a letter , can you deliver it by just giving the name of the person ? NO

You need to put address on it then the postman will reach that address, the postman does not need to know the name of receiver he only needs to know the address.

Your scanf like that postman it needs the address of memory location to deliver that value to the variable you want.

Abhinav Chauhan
  • 1,304
  • 1
  • 7
  • 24
  • In C, the name of an object is an *lvalue* that provides access to the object. This is why an assignment expression can change the value of an object without its address. The reason `scanf` needs an address is not because the name is inherently insufficient. – Eric Postpischil Mar 28 '20 at 10:36
  • may you edit my answer to fit that thing too in my analogy? – Abhinav Chauhan Mar 28 '20 at 10:58