Pointers

What is the purpose of pointer to pointer with double ** and just using 1 * and pointing it out to the address of the pointer, what i mean is:

What's the use of:

1
2
3
int ival = 1024;
int *p = &ival;
int **pi = &p;


VS:

1
2
3
int ival = 1024;
int *p = &ival;
int *pi = p;


What's the purpose of pointer to pointer declaration when we can just make another pointer pointing out just to the address of the pointer without the & operator, since
*p = pi
and both are pointers should be the same as
**p = &pi

Explanation would be great :)
Last edited on
closed account (48T7M4Gy)
A most important practical example of pointers to pointers with C-style arrays.

http://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new
In your first example your variable p (type int*) points to the memory address of ival (type int) and variable pi (type int**) points to the memory address of p (type int*)
So p and pi are actually pointing to different things and kemort has given you a nice link how pointers-to-pointers are used in 2d arrays.

However your understanding of the second case is not quite correct:

In this case p still points to memory address of ival but pi (now type int*) is assigned the value of p i.e. pi also points to the memory address of ival and so ival can be manipulated through either pointer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main()
{
    int ival = 1024;
    int *p = &ival;
    int *pi = p;

    std::cout << "Memory address pointed to by p: " << p << "\n";//same as below
    std::cout << "Memory address pointed to by pi: " << pi << "\n";//same as above

    ++(*p); ++(*pi);
    std::cout << ival << "\n";//prints 1026 (+1 from p, +1 from pi)
}


so you're not really making
another pointer pointing out just to the address of the pointer without the & operator,
but what you're really doing is assigning one pointer to another thereby sharing the ownership of the underlying object
but what you're really doing is assigning one pointer to another thereby sharing the ownership of the underlying object

Typically, raw pointers don't signify ownership at all.
Ownership in the sense that the raw pointers can each, separately, change the value of the underlying object as shown in the program but given the context of ownership elsewhere in the standard let's rephrase it a bit:
but what you're really doing is assigning one pointer to another thereby sharing the ownership of access to the underlying object
Last edited on
Topic archived. No new replies allowed.