Re: scanf and ampersand
- From: santosh <santosh.k83@xxxxxxxxx>
- Date: Tue, 29 Jan 2008 14:10:32 +0530
vlsidesign wrote:
I am a newbie to C, and was hoping to get a little bit better handle
on this until I get deeper into pointers, etc. I kind of understand it
some, but still unfamiliar because I haven't got to pointers and using
them yet. Here is my program:
#include <stdio.h>
int main()
{
char yourname[10];
int yourworth;
printf("what's your name? ");
Unless the output is terminated by a newline or fflush(stdout) is
called, the output may not immediately appear.
scanf(" %s", yourname);
printf("how many millions of dollars are you worth? ");
scanf(" %d", &yourworth);
The space character in the format string to scanf() is unnecessary.
printf("\n %s is worth %d \n", yourname, yourworth);
return 0;
}
I think that the scanf needs the second argument to be a pointer?
Yes.
I
believe that the value of a pointer is an memory address (which the &
ampersand address operator) retrieves?
Essentially yes. It could also be a null pointer value or indeterminate,
if uninitialised.
So when I put an ampersand in
front of the variable name "yourworth" that it returns the address,
which then the scanf then puts the value scanned into that memory
location?
Yes.
In the case of a string, which is just an array of
characters, like "yourname" above, it is really a pointer anyway, and
it's value is already an address, so the ampersand is not needed
anyway??
In most contexts in C an array name "degenerates" into a pointer value
to it's first element, i.e., &yourname[0] in this case. The exceptions
are when the array name is an operand to the address-of operator (&) or
the sizeof operator.
The comp.lang.c FAQ at http://www.c-faq.com has a lot of useful
information on common questions and misconceptions.
.
- References:
- scanf and ampersand
- From: vlsidesign
- scanf and ampersand
- Prev by Date: Re: xmalloc string functions
- Next by Date: Re: xmalloc string functions
- Previous by thread: Re: scanf and ampersand
- Next by thread: Fopen to create a file in a sub-folder (such as "Mygoal").
- Index(es):
Relevant Pages
|