Pointers

I'm trying to get the addresses of d2 and d3, and I know I am off. Then I want to point to the pointers. Any suggestions?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  1 #include <iostream>
  2 
  3 using namespace std;
  4 
  5 int main()
  6 {
  7    double d1 = 7.8;
  8    double d2 = 10.0;
  9    double d3 = 0.009;
 10 
 11    double* d;
 12    d = &d1;
 13    d = &d2;
 14    d = &d3;
 15 
 16    double **dp;
 17    dp = &d1;
 18    dp = &d2;
 19    dp = &d3;
 20 
 21    cout << "d1 = " << d1 << endl;
 22    cout << "*d = " << d << endl;
 23    cout << "dp = " << *(*dp) << endl;
 24 
 25    cout << "d2 = " << d2 << endl;
 26    cout << "*d = " << d << endl;
 27    cout << "dp = " << *(*dp) << endl;
 28 
 29    cout << "d3 = " << d3 << endl;
 30    cout << "*d = " << d << endl;
 31    cout << "dp = " << *(*dp) << endl;
 32 
 33    return 0;
 34 }
A pointer can only point to one thing at a time. If you look at, say, line 11-14, you declare only one pointer, then assign it the address of three different variables. In the end, it only holds the address of the third. Second, line 16 is specifically a pointer to a pointer. You can't make it hold the address of something that is not actually a pointer as well. In other words, a double-pointer only points to pointers, while pointers can point to... well, anything, really. But they can only point to one thing at a time.
I dont know what are you trying to achieve ,But I think this code will help you so much

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# include <iostream>
using namespace std;

int main()
{
    double d1 = 7.8;
    double d2 = 10.0;
    double d3 = 0.009;

    double *ptr1,*ptr2,*ptr3;

    ptr1 = &d1;
    ptr2 = &d2;
    ptr3 = &d3;

    cout << "The value of d1 is   : " << d1 << endl;
    cout << "Or at this way         " << *ptr1 << endl;
    cout << "The address of d1 is : " << &d1 << endl;
    cout << "Or at this way         " << ptr1 << endl;

    /// Same thing for the other varaibles

    double **dp;
    dp = &ptr1;

    cout << "The value of d1 is   : " << **dp << endl;
    cout << "The address of d1 is : " << *dp << endl;
    cout << "The address of dp is : " << dp << endl;

    return 0;
}


Hope that helps
Topic archived. No new replies allowed.