confusion with char *a and char a[NUM]

Rahul Dhesi dhesi%cirrusl at oliveb.ATC.olivetti.com
Wed Dec 12 14:27:15 AEST 1990


Let me give you a different way of understanding the difference between
char *A and char B[NUM].

After you have used malloc to assign NUM characters of storage for A,
both A and B can be used in a very similar way.  In some contexts any
reference to A or B is treated as the use of a pointer.

However, B is not a pointer.  It's just treated like one sometimes.  It
is a SYMBOLIC NAME FOR AN ADDRESS.  (And remember that a pointer is not
an address; it's a way of finding an address.)  In place of B you could
(if the language allowed it) use the absolute value of the address of
the array you call B.  You can pretend that the instant you use B, the
compiler converts it to the address for which B is a symbolic name.

A is not the same thing.  It is a VARIABLE, not an address.  The
variable is at some address, but when you use A, you usually
dereference that variable, and reach some other address.  This is why A
really *is* a pointer variable, while B is merely *treated* like one.

So, what happens when you do something like "A[3] = 7" or "B[3] = 7"?
In the first case, the compiler generates code to look at the CONTENTS
of the variable A, get those contents and add 3 to them, and treat the
result as an address.  B, however, is a symbolic name for an address.
The compiler generates code to directly take that address, add 3 to it,
and get another address.  In both cases, after the address is obtained,
a value of 7 is stored at that address.  (The above description is not
strictly accurate if A or B is on the stack.  For this description,
let's assume they are statically allocated and not in the stack.)

The terms "pointer" and "address" are often erroneously used with the
same meaning.  They are not the same.  An address is a location.  A
pointer is a way of getting to a location.  Think of the pointer as an
arrow pointing somewhere, and an address as the place the arrow is
pointing to.  A, the pointer, is an arrow, and it points to the address
where malloc() gave us memory.  B, the address, doesn't point anywhere
-- it *is* already an address.  A (a pointer) could point to B (an
address).  But B (an address) can never point to A, because B is not a
pointer.
--
Rahul Dhesi <dhesi%cirrusl at oliveb.ATC.olivetti.com>
UUCP:  oliveb!cirrusl!dhesi



More information about the Comp.lang.c mailing list