struct node
{
Item item; node *l, *r;
node(Item x) {item = x; l = 0; r = 0;}
};
typedef node* link;
link max(Item a[], int l, int r)
{
int m = (l+r)/2;
link x = new node(a[m]);
if (l==r) return x; // return a local pointer
x->l = max(a, l, m);
x-r = max(a, m+1, r);
Item u = x->l->item, v = x->r->item;
if (u>v) x->item = u;
else x->item=v;
return x; // return a local pointer
}
这是Robert Sedgewick撰写的“C++中的算法”(第252页,程序5.19)中的一段代码。在
max()
函数中,返回的变量是在函数内部创建的指针。我认为,在c/c++中不允许返回本地指针。所以我的问题是“编写这样的函数可以吗?”我不敢相信如此经典的书会犯这样的错误。还是我误解了原理?
请帮忙。谢谢。
最佳答案
x
不是“本地指针”,即指向本地变量的指针。 *x
是使用new
分配的。 x
指向动态分配的内存,并返回该指针就可以了。所以是的,可以编写类似这样的函数,并且书中没有错误。
关于c++ - 返回本地指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9779756/