一个简单程序的输出 [英] Output of a simple program

查看:63
本文介绍了一个简单程序的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有两个问题,它们的输出是什么,为什么?

Here are two problems what are their output and why?

#include<stdio.h>                      #include<stdio.h>
#include<conio.h>                      #include<conio.h>
int *call()                           int *call()
{ int x=5;                             { int x=5;
  ++x;                                   ++x;
  return &x;                             return &x;
}                                      }
void main()                             void main()
{ int *ptr;                             { clrscr();
                                         int *ptr;
  ptr=call();                            ptr=call();
  clrscr();                             
  printf("value:%d",*ptr);                printf("value:%d",*ptr);
}                                       }

推荐答案

它们实际上是相同的,并且都已损坏(您甚至无法编译它们).
在函数class中,您将返回一个指向临时变量的指针(函数返回后,x将被销毁).
main函数中,您正在调用不存在的函数"call".
They are practically identical and both broken (you can''t even compile them).
In function class you are returning a pointer to a temporary variable (x will be destroyed some time after the function returns).
in main function you are calling the not existing function ''call''.


Carlos是正确的:这是一个非常糟糕的主意.
如果您解决了编译问题,并实际调用了例程,则可能是randon输出的一种很好的形式,或者您的程序在不久的将来会爆炸.
这是因为默认情况下,C和C ++在堆栈上分配局部变量-这是所有例程共享的单个内存空间.当您返回指向局部变量的指针时,您将返回指向内存区域的指针,该内存区域在调用它们时将被其他例程重用-因此,为什么您的两个程序会产生不同的输出.在左边的示例中,ptr指向的局部变量使用的ve内存被clrscr 例程覆盖.
Carlos is right: that is a very bad idea.
If you fix the compilation problems, and actually call the routine, there is a very good chancve of either randon output, or you program blowing up in the near future.
This is because by default C and C++ allocate local variabals on the stack - which is a single memory space shared by all routines. When you return a pointer to a local variable, you are returning a pointer to an area of memory which will be re-used by other routines when they are called - hence why your two programs produce different outputs. In the example on teh left, theve memory used by the local variable that ptr points at is overwritten by the clrscr routine.


1:显示垃圾值,例如:-10.
2:显示正确的输出``6''和其他输入的增量值.
为什么在第二个选项中正确?
您能解释一下为什么clrscr()在此问题或例程方面给出不同的输出吗?
1:shows garbage value eg: -10.
2:shows correct output ''6'' and incremented value for other inputs.
why correct in second option?
can you explain it why clrscr() give different outputs in this question or respect to routines?


这篇关于一个简单程序的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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