在什么情况下可能需要使用多个间接(即,一个指针链,如Foo **)在C?
解决方法
@aku指出的最常见的用法是允许在函数返回后更改指针参数.
#include <iostream>
using namespace std;
struct Foo {
int a;
};
void CreateFoo(Foo** p) {
*p = new Foo();
(*p)->a = 12;
}
int main(int argc,char* argv[])
{
Foo* p = NULL;
CreateFoo(&p);
cout << p->a << endl;
delete p;
return 0;
}
这将打印
12
但是,还有其他一些有用的用法,如下面的示例,迭代字符串数组并将其打印到标准输出.
#include <iostream>
using namespace std;
int main(int argc,char* argv[])
{
const char* words[] = { "first","second",NULL };
for (const char** p = words; *p != NULL; ++p) {
cout << *p << endl;
}
return 0;
}