Richard Edwards wrote On 09/23/05 09:50,:
If I have the following declaration:
static char *list[1] = {0};
and I execute this code:
list[0] = malloc(10);
am I asking for problems?
Here's what I'm wondering. "list" is a 1 element array of char
pointers. The address that is stored in the 0th element of "list" is a
hard-coded 0. Now, I know that when a pointer is initialized to a
constant value (in practice, this is usually a string), the value that
the pointer points to should not be changed. In this instance, the
array pointer is pointing to 0.
Here, I think, is the root of your confusion. There
are two pointers wandering around in this code snippet:
- `list[0]' is a pointer to `char', a `char*'. You
initialize this pointer with a value of zero, which
is not the same thing as "pointing to zero."
- `list' itself is an array, and in nearly all cases
"speaking the name" of an array yields a pointer to
the array's first element. That is why you can
write `list[0]': the `list' part turns into a pointer
to the first array element, which is what you need
for array indexing. (Remember that `x[i]' is defined
as `*(x + i)' -- you need a pointer to get started.)
The malloc will change the value that
the array pointer points to to the allocated address. If the array
pointer was pointing to a _constant_ 0 that should not be changed, I
could see how this could cause problems.
It will not. The pointer's value is one thing, the value
of the thing pointed at (if any) is another. Your telephone
number is first in the list of emergency contacts (it is stored
in `emergency_contact_numbers[0]'), but when you go on vacation
somebody else's number goes into that spot. The pointer now
points to somebody else's telephone, but your telephone is
unchanged.
The only possible source of trouble is if the list of
emergency contacts was the *only* record of your telephone
number. In C, an "unlisted number" is usually called a
"memory leak," because once the program has lost track of
an object it can no longer do anything with it -- not even
throw it away. (And here the analogy begins to show some
cracks because you could still place outgoing calls from
your "unlisted number," but objects in C are "passive" and
can't do such things until tickled by the program -- but
if the program can't find them, it can't tickle them.)
--
Er*********@sun.com