主要功能范围规则. [英] scope rules of main function .

查看:72
本文介绍了主要功能范围规则.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

main()
int *p;
int*fun();
n
p=fun();

printf("%d",*p);

}


int *fun()
 {
  int d=20;
  return (&d);
}




在上面的函数中,当fun()返回时,p指针包含d变量的地址.但是,printf()语句失败,因为当fun()返回d时,由于范围规则,d被销毁了.我的问题是,当我们通过main通过引用调用时,我们可以访问这些值.在这种情况下,作用域规则为什么会失败.




In the above function ,when fun() return ,the p pointer contains the address of d variable . But, the printf() statement fails as when fun() returns the d is destroyed because of the scope rule . My question is that ,when we call by reference through main then we can access the values . in this case ,why the scope rules fails .

推荐答案

除了代码之外,没有其他失败.变量d是函数fun()中的局部变量,这意味着它不存在于该函数之外.因此,当fun()返回其地址时,它将返回一个不再存在的地址,这就是printf()失败的原因.如果fun()返回d的值,则您的代码可以在main()中将其打印出来.
Nothing fails, apart from your code. The variable d is a local variable in function fun() which means that it does not exist outside of that function. So when fun() returns its address it is returning an address that will no longer exist, which is why the printf() fails. If fun() returned the value of d then your code could print it out in main().


范围",如符号可见性"的语言规则中没有任何内容为此.

这就是数据/对象生命周期"的全部内容.您已陷入最基本的陷阱,您指向的数据项(d)的生存期短于指向它的事物.

如果您继续使用指向您随后称为"free()"或"delete"的对象或结构的指针而崩溃,那么没有人会感到惊讶.当然,指针指向的是已消失/可以重用的东西.然而,使用指向本地"(即基于堆栈)对象/变量的指针也可以做同样的事情.

如果确实可以认为是成功的话,这只是实现此目的的一种方法.在将局部变量的地址作为参数之一传递给它的同时创建线程是另一种方法.这应该是程序员需要提交到内存的那些红色标志"之一.
"scope", as in the language rules for symbol "visibility" has nothing to do with this.

"Data/Object Lifetime" is what this is all about. You have fallen into the most basic trap, you pointed to a data item (d) whose lifetime is shorter than the thing that points to it.

Nobody would be surprised if you crashed after continuing to use a pointer to an object or structure that you then called "free()" or "delete" on. Of course the pointer is to something that has disappeared / available for reuse. Yet it is possible to do the same thing with pointers to "local" (i.e. stack based) objects / variables.

This is just one way to accomplish this, if indeed it can be considered an accompishment. Creating a thread while passing the address of a local variable to it as one of the arguments is another. This should be one of those "red flags" that programmers need to commit to memory.


这篇关于主要功能范围规则.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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