What scenarios would ** be useful? [duplicate]
Possible Duplicate:
Uses for multiple levels of poin开发者_JAVA百科ter dereferences?
I saw a question about ** (pointer to a pointer) in C here. I'd like to know whats the point of this? When should I use it?
Whenever You need a pointer to a pointer :).
For example, if You want to dynamically allocate an array of pointers, operator new or malloc will return a pointer pointing to the first pointer in the array.
Other use might be, to pass a pointer to pointer, to a function, so the function can modify the original pointer. In C++, You can pass by reference, but not in C.
When you have a function which wants to increment a pointer to a c-string. This is needed for things like recursive-descent parsers where each rule is responsible for incrementing things...
In some variation of this:
void PutNewObjectHere(Class **dp) {
*dp = new Class;
}
Class *p;
PutNewObjectHere(&p);
delete p;
(Note, this is a silly example for illustration. It would normally return the new pointer. The concept, however, does occasionally come up in practice)
It's commonly used for out parameters that are pointers, e.g.:
bool GetSomeObject(SomeObject** object) {
*object = new SomeObject();
// ... initialize object or whatever ...
}
And you would call it like thus:
SomeObject* object;
if (GetSomeObject(&object)) {
// ... use object ...
delete object;
}
This is a common pattern where the callee allocates and the caller frees...
You want a C function to mutate a pointer passed as argument, and it's C so there's no pass-by-reference. Therefore you pass a pointer to the pointer. Here's a favorite example adapted from Dave Hanson's C Interfaces and Implementations:
void Bit_free(struct Bit_T **set) {
assert(set && *set);
free(*set);
*set = NULL;
}
By writing NULL
into the freed pointer, you prevent it from dangling.
This is called double indirection, meaning you have a pointer to another pointer, which in turn points to some useful data (or in rare cases yet another pointer).
There's a good article at Wikipedia that covers pointers in general and has a good section on double indirection.
In particular I've used these kind of pointers in the context of an array. For instance in my 8086 emulator project I had an array of function pointers. So it ended up looking like this:
instruction_functions[(int)opcode]();
This is also known as a jump table(sorta) and is used in a lot of places for optimization purposes.
精彩评论