Sunteți pe pagina 1din 9

Contents

Pointers...................................................................................................................... 1
Pointers, Arrays, and Structures..............................................................................1
Arrays......................................................................................................................... 1
Array Initializers...................................................................................................... 2
String Literals.......................................................................................................... 2
Pointers into Arrays.................................................................................................... 3
Navigating Arrays.................................................................................................... 4
Constants................................................................................................................... 4
Pointers and Constants............................................................................................ 5
References.................................................................................................................. 5
Pointer to Void............................................................................................................ 6
Structures................................................................................................................... 6

Pointers, Arrays, and Structures

Pointers
For a type T , T *is the type pointer to T . That is, a variable of type T *can hold the address of
an object of type T . For example:
c h a r c =a ;
c h a r *p =&c ;//p holds the address of c

or graphically:

Unfortunately, pointers to arrays and pointers to functions need a more complicated notation:
i n t *p i ;//pointer to int
c h a r **p p c ;//pointer to pointer to char
i n t *a p [1 5 ];//array of 15 pointers to ints
i n t (*f p )(c h a r *);//pointer to function taking a char* argument; returns an int
i n t *f (c h a r *);//function taking a char* argument; returns a pointer to int

Pointers, Arrays, and Structures


The fundamental operation on a pointer is dereferencing, that is, referring to the object pointed
to by the pointer. This operation is also called indirection. For example:
c h a r c =a ;
c h a r *p =&c ;//p holds the address of c
c h a r c 2 =*p ;//c2 == a

The variable pointed to by p is c , and the value stored in c is a , so the value of *p assigned to c 2
is a .

Arrays
For a type T , T [s i z e ]is the type array of s i z e elements of type T . The elements are indexed
from 0 to s i z e 1
. For example:

f l o a t v [3 ];//an array of three floats: v[0], v[1], v[2]


c h a r *a [3 2 ];//an array of 32 pointers to char: a[0] .. a[31]

The number of elements of the array, the array bound, must be a constant expression (C.5). If you
need variable bounds, use a v e c t o r
Multidimensional arrays are represented as arrays of arrays. For example:
i n t d 2 [1 0 ][2 0 ];//d2 is an array of 10 arrays of 20 integers
i n t d 2 [1 0 ][2 0 ][30];//d2 is an array of 10 arrays of 20 integers

Array Initializers
An array can be initialized by a list of values. For example:
i n t v 1 []={1 ,2 ,3 ,4 };
c h a r v 2 []={a ,b ,c ,0 };

An array can be initialized by a list of values. For example:


i n t v 1 []={1 ,2 ,3 ,4 };
c h a r v 2 []={a ,b ,c ,0 };

When an array is declared without a specific size, but with an initializer list, the size is calculated
by counting the elements of the initializer list. Consequently, v 1 and v 2 are of type i n t [4 ]and
c h a r [4 ], respectively. If a size is explicitly specified, it is an error to give surplus elements in an
initializer list. For example:
c h a r v 3 [2 ]={a ,b ,0 };//error: too many initializers
c h a r v 4 [3 ]={a ,b ,0 };//ok

If the initializer supplies too few elements, 0 is assumed for the remaining array elements. For
example:
i n t v 5 [8 ]={1 ,2 ,3 ,4 };

is equivalent to
i n t v 5 []={1 ,2 ,3 ,4 ,0 ,0 ,0 ,0 };

String Literals
A string literal is a character sequence enclosed within double quotes:
"t h i s i s a s t r i n g "

A string literal contains one more character than it appears to have; it is terminated by the null character
\ 0 , with the value 0 . For example:
s i z e o f ("B o h r ")==5

A string literal can be assigned to a c h a r *. This is allowed because the type of a string literal was c h a r *.
Allowing the assignment of a string literal to a c h a r *.however, an error to try tomodify a string literal through
such a pointer:
v o i d f ()
{
c h a r *p ="P l a t o ";
p[4]=e;//error: assignment to const; result is undefined
}

If we want a string that we are guaranteed to be able to modify, we must copy the characters
into an array:
v o i d f ()
{
c h a r p []="Z e n o ";//p is an array of 5 char
p [0 ]=R ;//ok
}

For example:
c o n s t c h a r *p ="H e r a c l i t u s ";
c o n s t c h a r *q ="H e r a c l i t u s ";

Whether two identical character literals are allocated as one is implementation-defined


For example:
c o n s t c h a r *p ="H e r a c l i t u s ";
c o n s t c h a r *q ="H e r a c l i t u s "
v o i d g ()
{
i f (p ==q )c o u t <<"o n e !\ n ";//result is implementationdefined
//...
}

Note that ==compares addresses (pointer values) when applied to pointers, and not the values
pointed to.
The empty string is written as a pair of adjacent double quotes, "", (and has the type c o n s t
c h a r [1 ]).
Long strings can be broken by whitespace to make the program text neater. For example:
c h a r a l p h a []="a b c d e f g h i j k l m n o p q r s t u v w x y z "
"A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ";

The compiler will concatenate adjacent strings, so a l p h a could equivalently have been initialized
by the single string:
"a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ";

It is possible to have the null character in a string, but most programs will not suspect that there
are characters after it. For example, the string " J e n s\000 M u n k " will be treated as " J e n s ".

Pointers into Arrays


In C++, pointers and arrays are closely related. The name of an array can be used as a pointer to its
initial element. For example:
i n t v []={1 ,2 ,3 ,4 };
i n t *p 1 =v ;//pointer to initial element (implicit conversion)
i n t *p 2 =&v [0 ];//pointer to initial element
i n t *p 3 =&v [4 ];//pointer to one beyond last element

or graphically:

The implicit conversion of an array name to a pointer to the initial element of the array
v o i d f ()
{
c h a r v []="A n n e m a r i e ";
c h a r *p =v ;//implicit conversion of char[] to char*
v =p ;//error: cannot assign to array
}

Navigating Arrays
Efficient access to arrays is the key to many algorithms. Access can be achieved either through a pointer to an array
plus an index or through a pointer to an element:
v o i d f i (c h a r v [])
{
f o r (i n t i =0 ;v [i ]!=0 ;i ++)u s e (v [i ]);
}

is equivalent to a traversal using a pointer:


v o i d f p (c h a r v [])
{
f o r (c h a r *p =v ;*p !=0 ;p ++)u s e (*p );
}

Subtraction of pointers is defined only when both pointers point to elements of the same array
v o i d f ()
{
i n t v 1 [1 0 ];
i n t v 2 [1 0 ];
i n t i 1 =&v 1 [5 ]&
v 1 [3 ];//i1 = 2
i n t i 2 =&v 1 [5 ]&
v 2 [3 ];//result undefined
i n t *p 1 =v 2 +2 ;//p1 = &v2[2]
i n t *p 2 =v 2 2
;//*p2 undefined
}

Constants
the concept of a user-defined constant, a c o n s t , to express the notion that a value doesnt change directly. This is
useful in several contexts.

The keyword c o n s t can be added to the declaration of an object to make the object declared a
constant. Because it cannot be assigned to, a constant must be initialized. For example:
c o n s t i n t m o d e l =9 0 ;//model is a const
c o n s t i n t v []={1 ,2 ,3 ,4 };//v[i] is a const
c o n s t i n t x ;//error: no initialize

Declaring something c o n s t ensures that its value will not change within its scope:
v o i d f ()
{
m o d e l =2 0 0 ;//error
v[2]++;//error
}

Pointers and Constants


Include pointer to constant and constant pointer:
v o i d f 1 (c h a r *p )
{
c h a r s []="G o r m ";
c o n s t c h a r *p c =s ;//pointer to constant
p c [3 ]=g ;//error: pc points to constant
p c =p ;//ok
c h a r *c o n s t c p =s ;//constant pointer
c p [3 ]=a ;//ok
cp =p;//error: cp is constant
c o n s t c h a r *c o n s t c p c =s ;//const pointer to const
c p c [3 ]=a ;//error: cpc points to constant
c p c =p ;//error: cpc is constant
}

The declarator operator that makes a pointer constant is *c o n s t . There is no c o n s t *declarator


operator, so a c o n s t appearing before the *is taken to be part of the base type. For example:
c h a r *c o n s t c p ;//const pointer to char
c h a r c o n s t *p c ;//pointer to const char
c o n s t c h a r *p c 2 ;//pointer to const char

You can assign the address of a variable to a pointer to constant because no harm can come from
that. However, the address of a constant cannot be assigned to an unrestricted pointer because this
would allow the objects value to be changed. For example:
v o i d f 4 ()
{
i n t a =1 ;
c o n s t i n t c =2 ;
c o n s t i n t *p 1 =&c ;//ok
c o n s t i n t *p 2 =&a ;//ok
i n t *p 3 =&c ;//error: initialization of int* with const int*
*p 3 =7 ;//try to change the value of c
}

References
A reference is an alternative name for an object. The main use of references is for specifying arguments
and return values for functions in general and for overloaded operators (Chapter 11) in particular.

The notation X &means reference to X . For example:


v o i d f ()
{
i n t i =1 ;
i n t &r =i ;//r and i now refer to the same int
i n t x =r ;//x = 1
r =2 ;//i = 2
}

we must initialize the reference. For example:


i n t i =1 ;
i n t &r 1 =i ;//ok: r1 initialized
i n t &r 2 ;//error: initializer missing
e x t e r n i n t &r 3 ;//ok: r3 initialized elsewhere

For example
v o i d g ()
{
i n t i i =0 ;
i n t &r r =i i ;
r r ++;//ii is incremented to 1
i n t *p p =&r r ;//pp points to ii
}

This is legal, but r r ++does not increment the reference r r ; rather, ++is applied to an i n t that happens
to be i i . Consequently, the value of a reference cannot be changed after initialization; it
always refers to the object it was initialized to denote. To get a pointer to the object denoted by a
reference r r , we can write &r r

Pointer to Void
A pointer of any type of object can be assigned to a variable of type v o i d *, a v o i d *can be assigned
to another v o i d *.a v o i d *can be explicitly converted to another type. Other operations would be unsafe
because the compiler cannot know what kind of object is really pointed to. Consequently, other operations result in
compile-time errors. To use a v o i d *, we must explicitly convert it to a pointer to a specific type. For example:
v o i d f (i n t *p i )
{
v o i d *p v =p i ;//ok: implicit conversion of int* to void*
*p v ;//error: cant dereference void*
p v ++;//error: cant increment void* (the size of the object pointed to is unknown)
i n t *p i 2 =s t a t i c c a s t <i n t *>(p v );//explicit conversion back to int*
d o u b l e *p d 1 =p v ;//error
double*pd2 =pi;//error
double*pd3 =staticcast<double*>(pv);//unsafe
}

Structures
An array is an aggregate of elements of the same type. A s t r u c t is an aggregate of elements of
(nearly) arbitrary types. For example:
struct address
{
c h a r *n a m e ;//"Jim Dandy"
l o n g i n t n u m b e r ;//61
char *street;//"South St"
c h a r *t o w n ;//"New Providence"
c h a r s t a t e [2 ];//N J
l o n g z i p ;//7974
};

This defines a new type called a d d r e s s consisting of the items you need in order to send mail to
someone. Note the semicolon at the end. Variables of type a d d r e s s can be declared exactly as other variables,
and the individual members can be accessed using the .(dot) operator. For example:
v o i d f ()
{
address jd;
j d .n a m e ="J i m D a n d y ";
j d .n u m b e r =6 1 ;
}

The notation used for initializing arrays can also be used for initializing variables of structure types.
For example:
a d d r e s s j d ={
"J i m D a n d y ",
6 1 ,"S o u t h S t ",
"N e w P r o v i d e n c e ",{N ,J },7 9 7 4
};

Using a constructor (10.2.3) is usually better, however. Note that j d .s t a t e could not be initialized
by the string " N J " . Strings are terminated by the character \ 0 . Hence, " N J " has three characters
one more than will fit into j d .s t a t e .
Structure objects are often accessed through pointers using the >
(structure pointer dereference)
operator. For example:
v o i d p r i n t a d d r (a d d r e s s *p )
{
c o u t <<p >
n a m e <<\ n
<<p >
n u m b e r <<<<p >
s t r e e t <<\ n
<<p >
t o w n <<\ n
<<p >
s t a t e [0 ]<<p >
s t a t e [1 ]<<<<p >
z i p <<\ n ;
}

When p is a pointer, p- >m is equivalent to (*p ).m .


Objects of structure types can be assigned, passed as function arguments, and returned as the

result from a function. For example:


addresscurrent;
a d d r e s s s e t c u r r e n t (a d d r e s s n e x t )
{
a d d r e s s p r e v =c u r r e n t ;
c u r r e n t =n e x t ;
returnprev;
}

S-ar putea să vă placă și