|
|
|
|||
Sometimes, you would like to use an
array data structure but may lack the information about the size of the array
at compile time. Take the example of telephone directory. You have to store one
lakh (100,000) names in an array. But you never know that the number of
entries may get double or decline in future. Similarly, you can not
say that the total population of the country is one crore (10 million) and
declare an array of one crore names. You can use one lakh locations now and
remaining will be used as the need arrives. But this is not a good way of
using the computer resources. You have declared a very big array while using
a very small chunk of it. Thus the remaining space goes waste which can,
otherwise, be used by some other programs. We will see what can be the
possible solution of this problem? Suppose you need an integer array of
size n after the execution of the program.
We have studied that if it is known at the execution of the program that an
array of size 20 or 30 is needed, it is allocated dynamically. The
programming statement is as follows: int* y = new
int[20]; It means we are requesting computer
to find twenty memory locations. On finding it, the computer will give the
address of first location to the programmer which will be stored in y.
Arrays locations are contiguous i.e. these are adjacent. These twenty
locations will be contiguous, meaning that they will be neighbors to each
other. Now y has become an array
and we can say y[0] =1 or y[5] = 15.
Here y is an lvalue. Being a pointer, it is a variable where we can store the
address of some variable. When we said int*
y = new int[20]; the new returns
the memory address of first of the twenty locations and we store that address
into y. As y is a pointer variable so it can be used on the left-hand side. |
|||||
|
BACK |
HOME |
NEXT |
||