DAY34
Monday, 30 July 2012
Detelina has moved today's office hours to tomorrow (TUESDAY)
at the usual time (12:05 - 1:00).
Today we might talk about:
-
How an array name like 'a" is like an "address" for the first element,
while a[0] is its value, and how we can look at nearby values using
quantities like a[1], a[2], ... a[100] even if the array only has 2 elements.
This helps us to think about the difference between address and value.
(example: array_bounds.c).
-
How, when we call scanf() using the ampersand operator, we are supplying
the address of a variable, which allows scanf() to modify that value;
instead of passing "&n", we can define a new kind of variable, a pointer,
which can store the address, and be passed to scanf().
(example: pointer_argument.c).
-
How the input arguments to a function are copies of the values, and
so changes to these values don't change the originals. How, if we pass
the address instead, we are able to change the original (example: arguments.c).
-
How to find out the "address" of any variable (example: pointer_print.c).
-
To find out the "address" of a variable and save that as a new
kind of variable, a pointer to the original variable (example: pointer_store.c).
-
How to use a pointer when a function expects the address of a variable.
The scanf() function is an example. (example: pointer_use.c).
Programs and functions we might talk about:
-
arguments.c shows that, if we pass a variable
by value to a function, the function can't change the original variable's
value; however, if we pass the address of the variable, the function has
access to the original variable and can change it.
-
array_bounds.c shows that, even if you
define an array A to be of size 5, the expression "A[6]" or "A[-4]" actually
is legal, and you might be able to tell what it means. This suggests how
C thinks of variable names as "addresses" in memory; then indexes just tell
you how far to walk from the basic address to get to the value you want.
-
pointer_argument.c,
a program which defines a variable "n", and a pointer "np" to the variable n.
The user is asked to enter a new value for n through scanf().
We don't pass "&n" to scanf(), but rather "np". But this is exactly the
same information, and once scanf() is done, we notice that the variable
"n" has changed, although the address "np" stays the same.
-
pointer_print.c,
a program which defines several variables, and then prints their addresses.
-
pointer_store.c,
a program which defines several variables, determines their addresses,
and saves these values as pointer variables.
-
pointer_use.c,
shows how pointers don't change when variables change (by addition, for instance).
Also shows how pointers can be used to change variables.
Last revised on 30 July 2012.