srikar2097 said:
<snip>
I think I get what you are trying to explain. Just one more doubt
though...
When we say *ptr2 = &b[0]; -------->1
richard said:
This assigns a value (i.e. the address of b's first
element) to the object pointed to by ptr2. But ptr2 doesn't point at
any object.
I agree to this explanation by richard.
Now when we write int *ptr2 = b[0]; --------->2
You mean &b[0], but yes.
How is this (i.e. 2) not same as (1).
Let's make the cases clear:
Case 1:
int b[10];
int *ptr2 = NULL;
*ptr2 = &b[0]; /* bug */
Case 2:
int b[10];
int *ptr2 = b; /* no bug */
Now I want to teach you a new language. This new language is exactly like C
in all respects save one - the $ operator is added. It means "contents
of", as in "$x = y;" means "x is a pointer to an object, and we give that
object the new value y". This means that we can keep * to mean purely "I
am now declaring a pointer".
Let's rewrite those cases in our new language:
Case 1:
int b[10];
int *ptr2 = NULL;
$ptr2 = &b[0]; /* bug */
Case 2:
int b[10];
int *ptr2 = b; /* no bug */
I hope that, using our new language with the $ deref operator, it becomes
clear that the assignment on line 3 of Case 1 is wrong. Since ptr2 doesn't
point to any object, we can't dereference it (and in fact we don't really
want to - we were mistaken in adding a dereference operator).
Case 2 shows more clearly that we don't have or want a dereference operator
here. All we want is to assign a pointer value to ptr2. In short, we want
the pointer to point at something.
Case 3 (below) is equivalent:
Case 3:
int b[10];
int *ptr2;
ptr2 = b; /* note - NO dereference */
In our new language, the * - in all three cases - merely means "I am
declaring a pointer object".
In C, however, the * does two jobs (well, actually more than two, but never
mind that for now). It doesn't just mean "I am declaring a pointer
object". It is also used for "I am dereferencing a pointer object". Since
you can't declare and dereference the same pointer at the same time, this
doesn't cause syntactical problems. But it does cause problems of
understanding.
It may (or may not) help to think of "int *p" as meaning "provided p points
somewhere, *p is an int".
--
Richard Heathfield <
http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <
http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999