返回指向局部变量的指针 [英] returning pointer to a local variable

查看:72
本文介绍了返回指向局部变量的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数返回指向局部变量的指针时会发生什么?

What happens when a pointer to a local variable is returned by a function?

例如

int* foo()
{
    int local;
    int* ptr = &local;
    return ptr;
}

编译器会发出警告,还是会编译并产生意外结果?

will compiler issue a warning or will it compile and produce unexpected results??

推荐答案

已经提出了类似的问题:

Similar kind of question has already been asked : Stack Overflow, local pointer

C中有一些东西可供编译器供应商以他们喜欢的方式实现.此类事物的行为未由创建者定义.编译器供应商可以以他们感觉轻松快捷的方式来实现这些事情.这属于同一类别.行为是不确定的,并且取决于您使用的编译器.

There are somethings in C which are left for compiler vendor to implement in the way they like. The behaviour of such things are not defined by the creators. Compiler vendors can implement such things as in the way they feel easy and faster. This falls in the same category. The behaviour is undefined and depends on the compiler you are using.

另一件事是使用一个以上的前递增(前递减)和/或后递增(后递减).当相同的代码在不同的编译器上运行时,您将获得不同的输出.

One more such thing is use of more than one pre-increment (pre-decrement) and/or post-increment (post-decrement). When the same code runs on different compilers, you'll may get different output.

这篇关于返回指向局部变量的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆