Pointer to Pointer query

S

Sac

Hello C Gurus,
Here is one more C behavior which I am not able understand:
int k,*p,*q;
p=&k;
q=p;
when I try to access K by **q compiler throws an error.
However
int a[ ]= {0,1};
int *b[ ] = {a,a+1};
I am able to access a[0] by **b.
As for as I understand array b and q both pointers.
For one pointer to pointer is allowed and for other compiler
gives out an error.
Can somebody enlighten me on this behaviour?

Thanks
Sac
 
J

jfbode1029

Hello C Gurus,
Here is one more C behavior which I am not able understand:
int k,*p,*q;
p=&k;
q=p;
when I try to access K by **q compiler throws an error.

As it should.

Look at the types of p and q; both are pointers to int, or int*. If q
== p, then *q == *p, and if *p == k (or p == &k), then *q == k. So
you would use *q to access the value at k, not **q. IOW, both p and q
are at the same level of indirection wrt k.

If you had done something like this:

int k, *p, **q;
p = &k;
q = &p;

then you would access k using **q.

Remember that in C, declaration mimics use; if the declarator is *q,
then that's the expression you use in your code to access the pointed-
to value, not **q.
However
int a[ ]= {0,1};
int *b[ ] = {a,a+1};
I am able to access a[0] by **b.

Again, look at the types of a and b. When an array identifier appears
in an expression (and is not the operand of either sizeof or &), its
type is implicitly converted from "array of T" to "pointer to T", and
its value is the address of the first element in the array.

The type of a is "2-element array of int." In the initializer for b,
the array identifier a "decays" into a pointer to int, and its value
is the address of the first element in the array (0).

In the expression **b, the type of b is first implicitly converted
from "2-element array of pointer to int" to "pointer to pointer to
int," and its value is set to the address of the first element. Thus,
*b gives you the value of the first element in b, which is a pointer
to int. **b gives you the value pointed to by that element, which is
the same as a[0].
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top