Pointers


Pointers
• A pointer is a datatype.
• You can create variables of this type as you
would of other types.
• Contains a memory address.
• Points to a specific data type.
int *pointer1 = &x;
• A pointer has to be declared just like any other variable -
remember a pointer is just a variable that stores an
address. For example,
int *p;
• is a pointer to an integer. Adding an asterisk in front of a
variable's name declares it to be a pointer to the
declared type. Notice that the asterisk applies only to
the single variable name that it is in front of, so:
int *p , q;
declares a pointer to an int and an int variable, not two
pointers.

The meaning of two new operators: &
and *
• The & operator returns the address of a
variable
For example:
int *p , q;
declares p, a pointer to int, and q an int and
the instruction: p=&q;
stores the address of q in p

Operator *
• If place * in front of a pointer variable then the result is
the value stored in the variable pointed at.
• That is, p stores the address, or pointer, to another
variable and *p is the value stored in the variable that p
points at.
• The * operator is called the de-referencing operator and
it helps not to confuse it with multiplication
• To declare a pointer add an * in front of its
name.
• To obtain the address of a variable use & in
front of its name.
• To obtain the value of a variable use * in
front of a pointer's name.
Now see if you can work out what the following
means:
int *a , b , c;
b = 10;
a = &b;
c = *a;
• Firstly three variables are declared - a (a pointer to
int), and b and c (both standard integers).
• The instruction is a=&b which stores the address of b
in a
• Finally c = *a stores the value in the variable pointed
to by a in c. As a points to b, its value i.e. 1O is stored
in c

More on Pointers
• You can print the address stored in a
pointer using the %p conversion specifier
Example: printf(“%p”, numPtr);
scanf() needs to know where to put the
value - it needs the address of the variable
as it takes pointers as parameters.
Example: int i;
scanf(“%d”, &i);

Why Pointers?
• To modify a variable in a function that is not a
global, or a local to that function
• To save space
• To save time
• To use dynamic memory
• Used extensively in linked structures

Pointers and Functions
• To enable a function to access and change an
object.
• For large structures it is more efficient.
• Use const specifier whenever a constant is
intended.

Pointers and Arrays
• The name array is equivalent to
&array[0]
• pPtr++ increments pPtr to point to the
next element of array.
• pPtr += n increments pPtr to point to n
elements beyond where it currently points.
• pPtr-qPtr equals i-j.

Pointers and Arrays (cont)
• array[0] is equivalent to *array
• array[n] is equivalent to *(array + n)



No comments

Powered by Blogger.