tags:

views:

85

answers:

5

i am using c++ and i have some trouble about pointers i know that if we declare some variable

int t=7;
int *p=&t;

*p gives adress of variable t but in c++ here also definition of **s why it is used ?i have read it but i have some misunderstanding please can anybody give me example how use?let take about given example

+2  A: 

For example, you can use this for creating an object in a function:

void create( Type** result )
{
    *result = new Type();
}

//somewhere else in code
Type* object;
create( &object );

this doesn't make much sence for void functions creating a single object, but in case the function needs some predefined return type or needs to create more than one object that will make sence. A classic example is IUnknown::QueryInterface() that must return HRESULT:

HRESULT CYourClass::QueryInterface( IID& iid, void** result )
{
    //inside you need to decide whether you know the iid passed, copy a pointer
    // into *ppv and then return apropriate HRESULT
}
sharptooth
can i use pointer of pointer to access variable for which we used first pointer?
Yes, sure - use `int** pp = ` It's usually called "pointer to pointer".
sharptooth
+3  A: 

Its a pointer to a pointer.

For example, if your operation was in a function:

void make_p(int **p, int *t) {
 *p = t;
}

int main() {
 int *p;
 int t;
 make_p(&p, &t);
}
Yann Ramin
+1  A: 

It's so we can change where other pointers are pointing to. Pointer to a pointer. Consider the following:

int *p1 = &j; // j is a int.
int *p2 = &k; // k is an int.

int **p;

p = &p1; //p points at p1.
*p = p2; //p1 now points to j because p2 is pointing to j.  
//Also we can do this through just plain old variables.
int l;
*p = &l; //p1 is now pointing at l
thyrgle
A: 

Just as int *p; defines a pointer to an int, int **s; defines a pointer to (a pointer to an int). This comes up usually in two cases:

First, if you want an array that holds pointers to an int, you would do something like: int **arr = malloc(sizeof(int*) * arr_size);

Second, when a function needs to return more than one value, it's common to have the extra values returned by reference. I.e.:

/* Return x, y and error code. */
int getVals(int *px, int *py) {
    *px = x;
    *py = y;
    return 0;
}

/* Return new object and error code. */
int newFoo(struct Foo **out_foo) {
    struct Foo *f = malloc(sizeof(struct Foo));
    f->value = 0;
    *out_foo = f;
    return 0;
}
Karmastan
+1  A: 
binW
I would argue that `*p` is not necessarily the *value* of the variable `t`, but rather the *variable* `t` itself :)
FredOverflow