Professional Documents
Culture Documents
Pointers in C++
Pointers in C++
On line 1 of the above of code, int variables i1, i2 and Isnt the way that the compiler handles incrementing and
i3 are declared and initialized with integer values 75, decrementing operations on pointers fascinating? Indeed
So far so good. The array name, numbers, is behaving And the following statement changes the value of the
exactly the same as other regular pointers. Can we fourth element of the array to 32.
conclude that array name can be used as like any other
pointer? Before rushing to the conclusion, let us apply
some arithmetic operations on numbers and let us see By using the name of the array, we accessed and
how it behaves. manipulated the array elements which we wanted. It was
First, let us apply the incrementing operation on fascinating, right? The above example shows how one-
numbers and let us point to the next element of the dimensional arrays can be used as pointers and the
array. Recall that incrementing pointers will make them associated restrictions while doing so. Can we say that
point to the next element in contiguous memory one-dimensional arrays and pointers are the same except
locations. Trying to point to the next element of the the arithmetic restrictions on array names? Not really.
numbers array through the following statement, There are subtle differences between them. We can pick
however, results in compilation error. two, for instance. The first one is the difference in the
memory address of pointers themselves and the memory
address referred by array names. The other is
initialization.
Array names are not like other pointers, after all. Can you
guess what the reason for the compilation error could be? We have seen that normal pointers have their own
It is the ++ operator. Since the data type of the array is memory space allocated for them. However, a separate
int, the above statement attempted to increment the value memory space is not allocated for array names, although
of numbers by sizeof(int). But, array names are they are considered as pointers. The memory address
associated with array names is that of the first array
constant pointers and their values cannot be changed and
element. In general, the memory returned by the address of
they only point to the first array element. This rule is not
operator on one-dimensional array names is the same the memory
limited for only incrementing, any other arithmetic
address of the first element.
operation which attempts to change the value of an array
name is illegal. We can now conclude that array names are We have also seen that arrays can be initialized during or
pointers with restrictions. after declaration (except for character arrays) using braces.
However, pointers cannot be initialized with braces even
If incrementing and decrementing is illegal on array
if they can be used as arrays.
names, we may think that, they are useless to point to
other array elements than the first one. However, that is Having the above differences between arrays and
not true at all. Array names can also be used to point to pointers, let us now consider character arrays in
all array elements. The reason why the above statement accordance with the above concepts. Do you remember
failed to point to the next array element is because the ++ what we said about character arrays in chapter two? We
operator attempted to change the value of numbers, said that they are given special consideration in C++. One
which is a constant pointer. Any valid arithmetic of the ways in which they are treated differently is, the
operation which doesnt attempt to change the value of whole character array can be printed by printing the array
numbers can point to other elements of the array as name. With the concept in mind, let us now investigate
well. Let us modify the above increment statement by this what made character arrays so special in C++. For this,
one: we will consider the following character array.
By: Asaye Chemeda Email: asayechemeda@yahoo.com 34
with pointer formal parameters to be invoked. One of
them has a data type for its formal parameter as const
To check that the array name program only refers to void* while the other one has const char*. When
the address of the first element, we can see the truth names of non-character arrays are passed as an argument,
values of the following logical statements. the overloaded function with the const void* as a
formal parameter data type will be invoked. As a result,
the memory address contained in the passed pointer,
which is the array name, will be printed by the <<
operator.
From the above, only the statement on Line 1 returns
true. Hence, the name program only points to the However, when the name of character arrays is passed,
first elements of the array. The following statements will the overloaded function with const char* as a data
print characters C, + and + respectively. type for the formal parameter will be invoked. This
function doesnt print the memory address contained in
the name of the passed character array. Rather, all the
characters in the array until the null character is
encountered will be printed. If the character array is not
Any of the elements of the character array can also be null-terminated, additional characters may also be printed.
manipulated by using the dereferencing operator. Mystery solved!
So far, we are getting what we expected and everything After all, character arrays behave in the same way as other
seems normal. The character array name program is arrays. The separate functions which handle exclusively
behaving just like any other array name. If so, what do you character arrays, however, treat them differently and
expect the output of the following statement will be? create the illusion that character arrays are different from
others.
We have seen how one-dimensional arrays can be used as
If the character array name program behaves like other pointers. Now, let us see the reverse- how pointers can be
array names, what is printed by the above statement used as one-dimensional arrays. Again, we will consider a
would be the memory address of the first program fragment of a code. Consider the following string array
array element. But, that is not what will be printed. All the and string pointer.
array elements, and probably additional characters, will
be printed. Even if we expect memory address of the
character C to be printed, all the characters in the array
will printed as a string. Mysterious, isnt it?
In the above code fragment, the name of the string array,
The reason for the above mystery to happen will be str, which is actually a pointer to the first element of the
solved by analyzing property of the << operator. The
array, C++ is assigned to a string pointer, p. If p is
way how the << operator will respond when it is called
dereferenced after Line 3, the return will be the string
into action is implemented in the iostream.h file. In
C++. If you answer what the following statement prints
the iostream.h, there are a number of overloaded
correctly, it means that you have fresh memory of
functions to handle the responses when this operator is
arithmetic operations on pointers.
called in a program.
Recalling our discussion on functions in chapter one,
overloaded functions have the same name but different
In the above statement, the value of p pointer is pre-
signatures. The overloaded function to handle the <<
incremented by sizeof(string) and then
operator is overloaded with several data types including
pointers. dereferenced. The pre-increment will make p point to the
second element of str array before being dereferenced.
Do you remember rule 1 of overloading which we The dereferencing returns the value of the second
discussed? The rule can be summarized as: when an element of the str array. Therefore, the above statement
overloaded function is called, the compiler tries to invoke prints the string is.
the function with the best match formal parameter as the
passed argument. Based on this rule, when pointers are Is that how a pointer is used as an array? If so, where is
passed to the function responding to calls made to << the array subscripting operator ([]) used? These are good
operator, there are two alternative overloaded functions
By: Asaye Chemeda Email: asayechemeda@yahoo.com 35
questions. Indeed, accessing array elements without Program 3.4[Correct].cpp
pointers is characterized by the usage of indexing through
the [] operator. The way the pointer p was used above
to access the elements of str array doesnt show that
pointers can be used as arrays.
Do you remember how name of array was used as a
pointer to access array elements? The basic idea at that
time was array name is a pointer and by dereferencing the
array name with integer addition or subtraction, the array
elements can be accessed and manipulated. Now, let us
see how array elements are accessed by indexing using the In the above program, p is initialized with the address of
array name. Since indexing starts from zero, str[0] the second element of str array. Therefore, the indexing
refers to the value of the first element of str array, for p starts from the second element of str array. Based
str[1] refers to the second and so on. on this, p[0] refers the string is and p[1] refers to
the third element of str array. Thus, the output of the
By initializing the p pointer with array name str, we cout statement on line 9 is the string awesome.
have synchronized them to refer to the memory address
of the first element of str array. Now, let us try to use The array name, however, always refers to the memory
the pointer p as str the way that str could be used as address of the first element. When 1 is added to an array
name and dereferenced, the second element of the array
p to access the array elements. If this is possible, i.e. if we
is always returned. The output of the cout statement on
can access and manipulate elements of str array by
line 10 is, therefore, the string is.
indexing p pointer without using the dereferencing
operator, we can say that pointers can indeed be used as One-dimensional arrays and pointers can be
arrays. interchangeably used to access and manipulate array
elements without much difference between them. Is this
Of course, it is possible to access and manipulate elements also the case for two-dimensional arrays? Can we apply
of one-dimensional arrays by indexing pointers. For what we discussed so far about pointers and arrays for
instance, p[0] refers to the value of the first element of two-dimensional arrays too? The answer for this is a
str array. The other elements can also be accessed and mixed yes and no. before looking into how two-
manipulated in a similar manner. The following statement dimensional arrays can be used as pointers or vice-versa,
changes the third element of str array from fun to let us see how elements of two-dimensional arrays are
awesome. stored in the memory.
When we consider two-dimensional arrays, what we
normally visualize is simple data type variables arranged
Note that, in the above statement, the array subscripting in two dimensions. If the array has (m+1) rows and (n+1)
not the dereferencing operator was used on the pointer p columns, we may expect it to be arranged as below in the
memory.
to change the third str element. Note that using index of 2
with pointers may not necessarily refer to the third array element. It
only means the third element from which the pointer is initialized
with the address of. For instance, if a pointer is initialized
with the address of the second element of the array, using
index of 2 with the pointer refers the fourth element of
the array not the third.
Dont you feel convinced that pointers can be used as
arrays? Hopefully, you do. Now, think about details. Figure 1: Two-dimensional array representation
Consider the following program and guess what will be
The question is: is this how two-dimensional arrays are
printed by the cout statements. Note that p is initialized
actually stored in the memory? In two dimensions with
with the address of the second element of str array. If
rows and columns? Not really. Two-dimensional arrays
you answered both of them correctly, you have
are stored in the memory as one-dimensional arrays. The
completely understood what we discussed so far about
above two-dimensional array will be stored in the memory
pointers and arrays. as:
By: Asaye Chemeda Email: asayechemeda@yahoo.com 36
is a pointer to a pointer, we cant assign it to a scalar
pointer to pointer.
Are you getting lost? Or is it getting interesting? May be,
if we use examples, it will be easier to understand and
more exciting. Let us consider the following array
declaration:
During our discussion in chapter two, we said that In the main function, a pointer to pointer pName is
functions cannot return arrays. However, this will not be defined on line 8. The pointer will be used to create the
a problem anymore. Can you guess why? Because we have dynamic array. On line 9, the customer is prompted to
pointers. Even though functions cannot return arrays, enter the number of names that he wants to enter. This is
they can return pointers. Obviously, pointers can act as just to show the dynamic nature of the array which we are
arrays. The logic is simple now. If functions can return going to create by entering different numbers of names
pointers and if pointers can act as arrays, why dont we for the dynamic array to hold. The number which will be
return arrays as pointers? You see another importance of entered by the user will be the number of rows in the
pointers. In general, if a function has to return an array, a array. Therefore, it will be stored in the rows variable.
pointer can substitute the array and the pointer can be
returned as an array. The purpose of the statement in line 11 will be explained
in the next chapter. On line 12, a dynamic memory is
Let us incorporate what we discussed about dynamic allocated for array of char pointers and the base address
arrays and returning arrays as pointers in a program which is returned to pName. Each element in the array of
improves the drawbacks that could happen if we use static
pointers will be used point to the base address of the
arrays. Here is the program.
characters in a single name. Therefore, the number of
Program 3.8[Correct].cpp elements in this array of pointers will be equal to rows
and the assignment to pName was made as such.
On line 13, a function named print is called by passing
pName as an argument. The formal parameter of the
print function is also made to conform to the data type
of the passed argument. Within print function, a
pointer to pointer is defined and it is initialized by the
pointer returned by read function.
The read function takes a pointer to a pointer of char
data type as a parameter. It is the read function which
reads the names entered by the customer and stores them
in the dynamic array accordingly. Note that, since the
read function returns a pointer to pointer, the return
type of the function is stated as such. In the read
function, a string variable sName is declared on line 18.
This variable takes the name of one customer. There are
two-four loops within the function. The outer for-loop
loops across the rows while the inner for-loop loops
across all the characters in a given name. Within the outer
for-loop, the customer is prompted to enter his name on
line 20. The statement on line 21, which will be explained
in detail in the next chapter, reads all the characters in a
string entered by the customer until the Enter key is
pressed. The entered string will be stored in the sName
variable.
Here comes another dynamic nature of the array which
we are going to create. The number of columns in a given
row will be determined after determining the number of
characters in the entered name. Isnt this what we wanted
to improve in program 3.7? The number of characters in