home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
BURKS 2
/
BURKS_AUG97.ISO
/
BURKS
/
LANGUAGE
/
C
/
PTRTUT
/
CH9X.HTM
< prev
next >
Wrap
Text File
|
1997-07-19
|
16KB
|
523 lines
<H2>CHAPTER 9: Pointers and Dynamic Allocation of Memory</H2>
There are times when it is convenient to allocate memory at
run time using <B>malloc()</B>, <B>calloc()</B>, or other allocation functions.
Using this approach permits postponing the decision on the size
of the memory block need to store an array, for example, until
run time. Or it permits using a section of memory for the
storage of an array of integers at one point in time, and then
when that memory is no longer needed it can be freed up for other
uses, such as the storage of an array of structures.
<P>
When memory is allocated, the allocating function (such as
<B>malloc()</B>, <B>calloc()</B>, etc.) returns a pointer. The type of this
pointer depends on whether you are using an older K&R compiler or
the newer ANSI type compiler. With the older compiler the type
of the returned pointer is <B>char</B>, with the ANSI compiler it is
<B>void</B>.
<P>
If you are using an older compiler, and you want to allocate
memory for an array of integers you will have to cast the char
pointer returned to an integer pointer. For example, to allocate
space for 10 integers we might write:
<PRE>
int *iptr;
iptr = (int *)malloc(10 * sizeof(int));
if (iptr == NULL)
{ .. ERROR ROUTINE GOES HERE .. }
</PRE>
If you are using an ANSI compliant compiler, <B>malloc()</B> returns
a <B>void</B> pointer and since a void pointer can be assigned to a
pointer variable of any object type, the <B>(int *)</B> cast shown above
is not needed. The array dimension can be determined at run time
and is not needed at compile time. That is, the <B>10</B> above could
be a variable read in from a data file or keyboard, or calculated
based on some need, at run time.
<P>
Because of the equivalence between array and pointer
notation, once <B>iptr</B> has been assigned as above, one can use the
array notation. For example, one could write:
<PRE>
int k;
for (k = 0; k < 10; k++)
iptr[k] = 2;
</PRE>
to set the values of all elements to 2.
<P>
Even with a reasonably good understanding of pointers and
arrays, one place the newcomer to C is likely to stumble at first
is in the dynamic allocation of multi-dimensional arrays. In
general, we would like to be able to access elements of such
arrays using array notation, not pointer notation, wherever
possible. Depending on the application we may or may not know
both dimensions at compile time. This leads to a variety of ways
to go about our task.
<P>
As we have seen, when dynamically allocating a one
dimensional array its dimension can be determined at run time.
Now, when using dynamic allocation of higher order arrays, we
never need to know the first dimension at compile time. Whether
we need to know the higher dimensions depends on how we go about
writing the code. Here I will discuss various methods of
dynamically allocating room for 2 dimensional arrays of integers.
<P>
First we will consider cases where the 2nd dimension is known
at compile time.
<H3>METHOD 1:</H3>
One way of dealing with the problem is through the use of the
<B>typedef</B> keyword. To allocate a 2 dimensional array of integers
recall that the following two notations result in the same object
code being generated:
<PRE>
multi[row][col] = 1; *(*(multi + row) + col) = 1;
</PRE>
It is also true that the following two notations generate the
same code:
<PRE>
multi[row] *(multi + row)
</PRE>
Since the one on the right must evaluate to a pointer, the
array notation on the left must also evaluate to a pointer. In
fact <B>multi[0]</B> will return a pointer to the first integer in the
first row, <B>multi[1]</B> a pointer to the first integer of the second
row, etc. Actually, <B>multi[n]</B> evaluates to a pointer to that
array of integers that make up the n-th row of our 2
dimensional array. That is, <B>multi</B> can be thought of as an array
of arrays and <B>multi[n]</B> as a pointer to the n-th array of this
array of arrays. Here the word <B>pointer</B> is being used
to represent an address value. While such usage is common in the
literature, when reading such statements one must be careful to
distinguish between the constant address of an array and a
variable pointer which is a data object in itself.
<P>
Consider now:
<PRE>
--------------- Program 9.1 --------------------------------
/* Program 9.1 from PTRTUT10.HTM 6/13/97 */
#include <stdio.h>
#include <stdlib.h>
#define COLS 5
typedef int RowArray[COLS];
RowArray *rptr;
int main(void)
{
int nrows = 10;
int row, col;
rptr = malloc(nrows * COLS * sizeof(int));
for (row = 0; row < nrows; row++)
{
for (col = 0; col < COLS; col++)
{
rptr[row][col] = 17;
}
}
return 0;
}
------------- End of Prog. 9.1 --------------------------------
</PRE>
Here I have assumed an ANSI compiler so a cast on the void
pointer returned by <B>malloc()</B> is not required. If you are using
an older K&R compiler you will have to cast using:
<PRE>
rptr = (RowArray *)malloc(.... etc.
</PRE>
Using this approach,<B> rptr</B> has all the characteristics of an
array name name, (except that rptr is modifiable), and array notation may be used throughout the rest of
the program. That also means that if you intend to write a
function to modify the array contents, you must use COLS as a
part of the formal parameter in that function, just as we did
when discussing the passing of two dimensional arrays to a
function.
<H3>METHOD 2:</H3>
In the METHOD 1 above, rptr turned out to be a pointer to
type "one dimensional array of COLS integers". It turns out that
there is syntax which can be used for this type without the need
of <B>typedef</B>. If we write:
<PRE>
int (*xptr)[COLS];
</PRE>
the variable <B>xptr</B> will have all the same characteristics as the
variable <B>rptr</B> in METHOD 1 above, and we need not use the
<B>typedef</B> keyword. Here <B>xptr</B> is a pointer to an array of
integers and the size of that array is given by the <B>#defined
COLS</B>. The parenthesis placement makes the pointer notation
predominate, even though the array notation has higher
precedence. i.e. had we written
<PRE>
int *xptr[COLS];
</PRE>
we would have defined <B>xptr</B> as an array of pointers holding the
number of pointers equal to that #defined by COLS. That is not
the same thing at all. However, arrays of pointers have their
use in the dynamic allocation of two dimensional arrays, as will
be seen in the next 2 methods.
<H3>METHOD 3:</H3>
Consider the case where we do not know the number of elements
in each row at compile time, i.e. both the number of rows and
number of columns must be determined at run time. One way of
doing this would be to create an array of pointers to type<B> int</B>
and then allocate space for each row and point these pointers at
each row. Consider:
<PRE>
-------------- Program 9.2 ------------------------------------
/* Program 9.2 from PTRTUT10.HTM 6/13/97 */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int nrows = 5; /* Both nrows and ncols could be evaluated */
int ncols = 10; /* or read in at run time */
int row;
int **rowptr;
rowptr = malloc(nrows * sizeof(int *));
if (rowptr == NULL)
{
puts("\nFailure to allocate room for row pointers.\n");
exit(0);
}
printf("\n\n\nIndex Pointer(hex) Pointer(dec) Diff.(dec)");
for (row = 0; row < nrows; row++)
{
rowptr[row] = malloc(ncols * sizeof(int));
if (rowptr[row] == NULL)
{
printf("\nFailure to allocate for row[%d]\n",row);
exit(0);
}
printf("\n%d %p %d", row, rowptr[row], rowptr