Re: c question

From: A. Bolmarcich (aggedor_at_earl-grey.cloud9.net)
Date: 08/27/04


Date: Thu, 26 Aug 2004 22:35:00 -0000

In article <d94c72f0.0408261334.2fce1edf@posting.google.com>, jim wrote:
> I am reading c:the complete reference, fourth edition by herbert
> schildt.
> I think the following program has a bug
[snip program]
> Although the above version runs, I think the definition of dic is not
> correct. the correct version should be
[snip program]

What Schildt wrote works because the "wrong" declaration of dic

  char *dic[][40]

is compensated for by the cast in the assignment

  p=(char **)dic;

In Schildt's version the array initializer makes the size of the []
dimension of dic 1 and sizeof(dic) == 40*sizeof(char *). Don't try
to use 40 initial values with Schildt's version.

What you wrote is more correct and you can remove the cast from the
assignment

  p=(char (*)[40])dic

because in your version the type of the expression

  dic

is char (*)[40]. In general, the few casts a program needs, the
better. In your version the array initializer makes the size of
the [] dimension of dic 10 and sizeof(dic) == 10*40.

Because the program never uses dic as a two-dimensional array, a
better version would be to take Schildt's version but define dic as

  char *dic[]={
    "atlas","A volume of maps",
    "car","A motorized vehicle",
    "telephone","a communication device",
    "airport","A flying matchine",
    0
  };

and remove the cast from the line

  p=(char **)dic;

In this version sizeof(dic) == 9 * sizeof(char *), where the
factor of 9 occurs because the array is initialized with 9 values.