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
}
这是《C++算法》一书第252页5.19程序中的一段代码。在函数
max()
中,返回的变量是在函数内部创建的指针。据我所知,在C/C++中不允许返回局部指针。因此我的问题是:“这样写一个函数是否可行?”我无法相信这样经典的书籍会犯这样的错误。或者是我理解有误? 请帮忙解答。谢谢。
c
中返回指向本地变量的指针会导致警告,除非你知道自己在做什么,否则应该避免这样做,但它确实可以工作。不确定c++
是否将其改为错误。 - twain249int *fun() { int a = 3; return &a;}
并使用gcc编译它,看看会发生什么,结果我得到了一个警告。所以我想我能确定的是gcc对此会发出警告。 - twain249