Notes on C
It is important to realize that an array is different from a pointer, although both can
be of the same type. When we write
then both a and p are of type pointer-to-int, but writing
would be wrong, as a always refers to a fixed address that cannot be changed. On
the other hand, this is correct:
Since p is a pointer we can assign an address to it. We say that p is an lvalue
whereas a is not.
The address assigned to p is actually the address of a so the following
assignment has exactly the same meaning:
Assignment is not the same as initialization. These are both wrong:
The following definition with initialization is fine:
The first three array elements are assigned and all other elements are set to zero
due to the ininitialization. Without initialization the value of each element would
have been undefined.
We cannot initialize over a pointer:
But note that this is perfectly fine:
Assignment over a pointer is possible after we have made it point to an address:
Strings stored in character arrays are terminated by a zero. So to store a five
character string we need a six element character array.
We need to take this into account when allocating a pointer:
Since the character array is not an lvalue we cannot do this:
We need to do this instead:
or properly initialize the array:
The compiler now fills the array with the string being kept in memory, which is
somewhat wasteful. If we want to keep the string unchanged we can use a constant
pointer like this:
The first const disallows us to change the characters.
The second const disallows us to reassign the pointer.