nair SL
11/12/2008 1:58:00 PM
On Nov 11, 1:03 am, gw7...@aol.com wrote:
> On 10 Nov, 08:48, nair SL <anoop...@gmail.com> wrote:
>
>
>
> > I want to understand whether this following piece of code is giving me
> > junk result becoz I'm trying to access values out of scope?
>
> > int* array_display(){
> > int array1[4] = {11,22,33,44};
> > int *qq = array1;
> > return qq;
>
> > }
>
> > int main()
> > {
> > int *pp;
> > pp = array_display();
>
> > for(i=0; i<4; ++i,++pp) {
> > int temp = *(pp); //case 1
> > // int temp = *(pp+1); //case 2 returns 22 first and
> > subsequent junk
> > cout<<"pp array ->- "<<temp<<endl;
> > }
> > return 0;}
>
> I think you're right about the problem, but you are using slightly the
> wrong name for it.
>
> As the program stands, array1 disappears when the function
> array_display finishes. So when you try to read it in main, it's gone
> before you finish.
>
> You can fix this problem by putting the word "static" in front of the
> "int array1". This will cause the array to exist all the time the
> program is running, and so (if you also add "int i;" to main, and a
> suitable header) the program will work.
>
> The property of how long a variable hangs around for is called its
> "lifetime". In your program as stated, the lifetime of the array was
> while array_display was running, with my changes, the lifetime of the
> array is the time the program is running.
>
> The "scope" of a variable is the places in the program where you can
> refer to it by name. In your program, and indeed in my modification of
> it, the scope of array1 is the routine array_display. You can't refer
> to the array by the name "array1", or by the name "qq", in main. But
> if the lifetime of the array is still running, you can refer to it
> using another variable which has the same value - in this case, using
> pp.
>
> Hope that helps.
> Paul.
Thanks for all the Tips.
That helped me a lot.