简体   繁体   中英

Clarity between Pointer-to-Pointer, Value-of-Pointed address and 2D-Array access

Can someone set the path straight on the disparities between these ubiquitous, as It can get a bit mind blowing.

For example if I have a 2D array such as rec[3][2] , the following access means the same;

rec[0][0] = **rec
rec[i][0] = **(rec + i)
*(*(rec + i) + j) = rec[i][j]

If this is the case then what are the meaning of these:

#include <stdio.h>
double *recptr[3];
int i=1;

main()
{
 double n1=12.0;
 doublw n2=3.4;

 recptr[0]= &n1;
 recptr[1]= &n2;

 printf("Amt: %.2f\n", **(recptr + i));
}

What is **(recptr + i) , Is this access to 2D pointer or ponter-to-pointer reference?

foo(ptr2ptr)double **ptr2ptr;
{
 int i=1, j=0;
 if(**(ptr2ptr +i) > **(ptr2ptr + j))
 {
  double *tmp= *(recptr +i);
 }
}

Again what is the difference between *(recptr +i) and **(ptr2ptr +i) ?! is the later also 2D access or access to pointer-2-ponter reference and the earlier the object pointed to?

double *recptr[3];

This creates an array of 3 pointers to double (double*) .
Now, in the main() , we have double n1 = 12.0f and double n2 = 3.4f .

Now we assign the address of n1 (&n1) to recptr[0] (First element of the array which just happens to point to doubles, so now it points to an address of a double (our n1) which is ok.) -> Please do note this is NOT a reference (in theory). We are taking the address of n1.

We do the same thing with n2, so now recptr[1] is a pointer that points to the address of n2.

Now we print **(recptr + i) -> This means the following:

We take the address of the first element of the array (recptr evaluates to the address of the aray), we offset this address by i (which just happens to be 1). Now please do note that we don't move 1 byte further, we move sizeof(double*) bytes further.

Now, we dereference this position *(recptr + i) which is (address of first element + sizeof(double*) bytes) away and what do we see ? Well, it's a pointer to a double (Or in other words, it's just an address of n2). So we need to dereference yet again to actually see the value that this particular pointer points to, hence **(recptr + i) .

So, the first dereference just gives us the correct "cell" of our recptr array but in that cell, there's a pointer to a double, so in order to get to it's value, we need to dereference yet again.

(We then indeed print 3.40 since it's address happens to live in the second cell of recptr array.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM