We saw in the last lesson that the two declarations
int A[10];
int *A;
both declare A to be a pointer to an integer (or, equivalently, an array of
integers). Nevertheless, there are two crucial differences between the two
declarations. What are they?
Click here for the answer
Given this, how do you think the following three declarations compare?
char A[4][4];
char *B[4];
char **C;
Click here for the answer
Here's a way to visualize what's going on. In the first case,
A: [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ]
A is a name for the constant address of a 4x4 block of storage locations. In
the second case,
B: [ ] [ ] [ ] [ ]
B is a name for the constant address of a block of of 4 storage locations,
each of which can someday contain a pointer to a character
(or characters). Once we initialize these four storage locations, we might
have a picture like
B: [ ] [ ] [ ] [ ]
| | | |
\|/ \|/ \|/ \|/
[ ] [ ] [ ] [ ]
[ ] [ ] [ ]
[ ] [ ]
[ ]
Notice that each of the four pointers can point to a different size block
of characters. (Thus the name ``ragged array''.)
Finally, in the third case
C:[ ]
C is the name of a variable that can someday be assigned a pointer to a
pointer to characters. For example, we might initialize C as
C:[--]-->[ ] [ ] [ ] [ ]
and could then initialize each of the four new storage locations as we
did in the example for B to obtain
C:[--]-->[ ] [ ] [ ] [ ]
| | | |
\|/ \|/ \|/ \|/
[ ] [ ] [ ] [ ]
[ ] [ ] [ ]
[ ] [ ]
[ ]
The important thing is to realize that whereas the value of C can be changed
(via assignment), the values of A and B cannot. Further, whereas the values of
each of the B[i] and C[i] can be changed, the values of the A[i] cannot. On
the other hand, A, B, and the A[i] are actually preallocated, whereas C, the
B[i], and the C[i] are not.
However, once they are all fully initialized, A[i] (or B[i] or C[i]) will be a
pointer to a character (i.e., a string), and A[i][j] (or B[i][j] or C[i][j])
will be a character.
Hamlet Project
hamlet@cs.utah.edu