[Courses] C Programming For Absolute Beginners, Lesson 2: Fun With Printf, Scanf, Puts, and Variables
Akkana Peck
akkana at shallowsky.com
Tue Feb 21 20:27:56 UTC 2012
Carla Schroder writes:
> You must use the & symbol in front of your variable or it won't
> work. If you want to jump ahead this is your introduction to using pointers,
> which is pointing to a specific location on memory. Pointers is a weird and
> complicated subject to explain, so for now I'm going to leave it at "don't
> forget the & symbol when you're playing with scanf." (Anyone who wants to
> chime in with their own explanation of pointers is welcome!)
I'll give that a try -- just a very general explanation to whet your
appetite for later lessons.
Suppose you have an integer variable:
int i = 42;
The variable i lives somewhere in your computer's memory -- doesn't
matter exactly where, the OS takes care of all that housekeeping.
Now suppose you want to pass that variable to a function that will
do something with it:
do_something_with(i);
In C, what happens is that the function do_something_with() gets
the number 42. It has no way of telling whether that 42 came from
a variable that lives in a particular place in memory.
Why does that matter? Because it means that do_something_with()
can't possibly modify i. After you call do_something_with(i);
you can be confident that i will still be 42, regardless of what
happens inside the function.
(This is called "Call by value", and you can read lots more about
it at http://en.wikipedia.org/wiki/Call_by_value#Call_by_value ).
That's all very well until you call a function like scanf(), where
you *need* to be able to change the variable you pass in.
So if I call
scanf("%d", &i);
I'm not passing in the current value of i, 42. Instead, I'm passing
in a pointer to i, which tells scanf where i is in memory. That way,
once scanf reads in a value, it can stick that value into memory in
place of the 42 that used to be there.
So that's all a pointer is -- a way of pointing to where a variable
lives in memory, so you can modify it more easily. &i is a pointer
to where the variable i is in memory. If it helps, you can think of
&i as saying "Here's i, and you can change its value if you like."
...Akkana
More information about the Courses
mailing list