Abu Abu - 7 days ago 5
C Question

How to print pointer to pointers

I am a newbie trying to understand the working of double pointers and to print double pointers. I increment

m
by one but it's always pointing to the last value pointed by
p
. Can someone please help me?

#include <stdio.h>

int main () {
/* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
double **m;
int i;

p = balance;
m = &p;
/* output each array element's value */
printf( "Array values using pointer\n");

for ( i = 0; i < 5; i++ ) {
printf("*(p + %d) : %f\n", i, *(p+i) );
}

for ( i = 0; i < 5; i++ ) {
printf("**(m + %d) : %f\n", i, *m);
m++;
}

printf( "Array values using balance as address\n");

for ( i = 0; i < 5; i++ ) {
printf("*(balance + %d) : %f\n", i, *(balance + i) );
}
return 0;
}

Answer

Your array balance is like this

+--------+--------+--------+--------+--------+
| 1000.0 |    2.0 |    3.4 |   17.0 |   50.0 |
+--------+--------+--------+--------+--------+

After you initialize p and m it is like this:

+---+
| m |
+---+
|
v
+---+
| p |
+---+
|
V
+--------+--------+--------+--------+--------+
| 1000.0 |    2.0 |    3.4 |   17.0 |   50.0 |
+--------+--------+--------+--------+--------+

That is, m points to the location of p, and p points to the first value of the balance array.

When you dereference m (i.e. when you do *m) you get the value of where m is pointing. This value is another pointer (p) that you need to dereference to get to an element in the array.

Using m the second element in balance (i.e. balance[1]) is (*m)[1].


Now if you increment m (with e.g. m++) it will point to the next element of p:

     +---+
     | m |
     +---+
     |
     v
+---+
| p |
+---+
|
V
+--------+--------+--------+--------+--------+
| 1000.0 |    2.0 |    3.4 |   17.0 |   50.0 |
+--------+--------+--------+--------+--------+

You can clearly see the problem here: It no longer points to p and you can no longer us it to access the balance array. Dereferencing m after the increment will lead to undefined behavior.

Also, for any pointer or array, the array-indexing expression and the pointer arithmetic expression are equal. So for balance, the expression balance[i] is equal to *(balance + i). There is really no difference between them.