[A89] Re: c trouble


[Prev][Next][Index][Thread]

[A89] Re: c trouble



<< The major difference is that assigning a multidimension array by using
"char foo[x][y]" gives it a static, defined size, while using "char **foo "
doesn't restrict the program from overwriting the array with other
variables, since it hasn't reserved a specific size. For example, if you had
"char foo[3][3]", you'd reserve 9 bytes for characters; however, "char
**foo" would only reserve the first byte at the location given for foo. >>

I'm sorry, but this is completely, fundamentally wrong in several ways - so
wrong that it's difficult to correct.  I'll at least point out two ways.

First, "char **foo" does NOT reserve space for any items; not even for "the
first byte at the location given for foo"!  [Not only that, if it did
reserve space, it would first reserve space for a char* - dereferencing only
one level at a time - and then perhaps also for a char, but that doesn't
matter because this is all fundamentally wrong and it doesn't work that way
at all.]  It allocates a variable which stores the location of a pointer to
a char; it does NOT allocate space for the pointer to a char being pointed
to, nor does it allocate space for the char that THAT points to.  You'd need
to allocate the space yourself with something like this:

    char data = [...];
    char *bar = &data;
    char **foo = &bar;

Second, you've got the difference between "char food[x][y]" and "char **foo"
completely wrong.  "char foo[x][y]" is a two-dimensional array of items
stored in CONTIGUOUS memory.  "char **foo", if being used in the context of
arrays, is a two-dimensional RAGGED array - dereference once and you have
the first item in an array of pointers to each "row" of the two dimensional
array, then derefence one of those to get the first item in that row.  In a
ragged array, the rows need not all be the same length, they aren't
necessarily stored in contiguous memory (you'll need to allocate the space
for and construct the ragged array more-or-less manually, so you control
this), it needs more space to store a whole extra sets of pointers, and can
be either faster or slower to obtain data from depending on exactly what
you're doing.

    -Scott