home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Black Box 4
/
BlackBox.cdr
/
progc
/
c_all592.arj
/
TI802.ASC
< prev
next >
Wrap
Text File
|
1992-02-25
|
2KB
|
67 lines
PRODUCT : C++ NUMBER : 802
VERSION : ANY
OS : PC DOS
DATE : February 25, 1992 PAGE : 1/1
TITLE : char ** Vs. char[][]
One of the pitfalls of the C language is based on the assumption
that char **apple, char *orange[], and char cherry[][] are
equivalent declarations. In practice, the types are virtually
identical, but some subtle differences can lead to unintended
results.
'apple' is a pointer to a pointer, 'orange' is an array of
pointers, and 'cherry' is simply a two dimensional array. If
'apple' is declared as above, then expressions like apple[1], and
*apple[3] are valid because the compiler knows what the latter
expressions mean because it knows what type 'apple' really is.
But, suppose the compiler had been told the incorrect type? What
happens then? Well, this can only happen if the variable is
defined in one module, say as 'char apple[][]' and declared
external in another, as 'extern char **apple'. In the second
module, when we use expressions for apple, the compiler will
interpret them as if apple were a char ** type, since that is how
it's declared (the compiler knows nothing of the definition in
module one). What this means for the implementation is this:
Let's compare char **apple with char cherry[][] 'apple' is the
label for a pointer, so to get at the pointer, the compiler
dereferences the label to get the first pointer. Two more
dereferences will be required to get at the data now. But
'cherry' is the label of an array, not a pointer. So to access
an array member, the compiler needs to calculate the offset into
the array and use that as an offset of the label 'cherry'. There
is considerable difference between looking at the data offset
from a certain value, and dereferencing a sequence of pointers.
These differences will cause the data to appear corrupted, when
in reality, the data is fine and it is the measuring tool that is
incorrect. The moral of this is, of course, to remember the
distinction between a char ** type and a char [][] type and not
to mix declarations of such types.