The Sorter
The Sorter

Reputation: 7

Changing value in pointer to pointer

So i have a function similar to that (simplified example):

void somefunction(structuraltype *something) {

    something->variable = 6;

}

And as you can see i can easily access values using ->

But i realised that i must use pointer to pointer instead of a single pointer.
Can you please explain to me how should i access value in this situation?

void somefunction(structuraltype **something) {

    something???variable = 6;

}

Upvotes: 0

Views: 379

Answers (2)

Galik
Galik

Reputation: 48605

The equivalent of this:

void somefunction(structuraltype* something) {
    something->variable = 6;
}

is this

void somefunction(structuraltype* something) {
    (*something).variable = 6;
}

You can apply that for every level of indirection:

void somefunction(structuraltype** something) {
    (*(*something)).variable = 6;
}

The outer level of indirection can always be replaced by -> as in:

void somefunction(structuraltype** something) {
    (*something)->variable = 6;
}

But it's probably more usual to use a reference to a pointer than a ponter to a pointer:

void somefunction(structuraltype*& something) {
    something->variable = 6;
}

Upvotes: 2

Remy Lebeau
Remy Lebeau

Reputation: 595329

Simply dereference the first pointer to access the second pointer, which you can then use to access the object members:

void somefunction(structuraltype **something) {    
    (*something)->variable = 6;    
}

Upvotes: 4

Related Questions