
Why use address-of operator (&)??
Quote:
> Why we must use address-of operator (&) when reading numeric input using
> scanf( ) function?
> example :
> /* start source */
> char input;
> main ( )
> {
> printf("Enter a number : ");
> scanf ("%c", &input);
> return 0;
> }
> /* end of source */
> While we don't have to use & when reading string input using the same
> function.
> Steven Yik
> Beginner in C
Because you can only return data via a parameter list indirectly. When
you pass variables to a function - e.g.
int a,b,c;
/* ... more code... */
function1(a,b,c);
the *values* contained by a,b,c are passed. The called function then
has no knowledge of where a,b,c themselves exist in memory. This means
that the function itself cannot change the values of a,b,c. So if you
were to try, for example:
scanf("%d",a);
the scanf function would not know where a was to fill it with the
number entered in the input stream. Hopefully, your compiler will
barf too, because you're trying to use an integer parameter where
you should be using a pointer.
If, on the other hand, you had something like:
int a,b,c;
/* ... more code... */
function2(&a,&b,&c);
now, your are passing the addresses of a,b,c to your function rather
than their contents. This means that the function knows where they
are and can write to their addresses to change their values. Thus:
scanf("%d",&a);
will pass the address of a to scanf, scanf reads an integer from the
input stream and writes it to the address supplied, which is the
address of a in this case - thus scanf("%d",&a) puts the number input
into a.
The reason you don't have to pass strings with the & operator is that
strings are stored via pointers anyway, or in arrays, which are
converted to pointers when passed as function parameters - e.g.
char astring[40];
char *bstring;
bstring=malloc(40); /* In a real situation NULL checking would be done
*/
scanf("%s",astring);
scanf("%s",bstring);
bstring is already a pointer - the address of the beginning of a string,
which is passed to scanf. astring is an array, the start address of
which is passed to scanf without any further need for the address-of
operator on your part.
- hope this makes sense !
Simon.