Login or Sign up Help | Site Map
Connecting Tech Pros Worldwide

Local array scope

Question posted by: D. Susman (Guest) on July 4th, 2008 12:35 PM
Hi,

When the method "foo" ends, shouldn't the arr[2] array be gone (due to
scope termination) and the pointer in class A be invalid? However,
when I run the program, I get "2". It seems to that I get this result
by luck; in further executions, I may get some other value. Am i
right?
class A
{
public:
A( int* ptr ){ arr = ptr; }
int* getArr(){ return arr; }
private:
int* arr;
};

A foo( )
{
int arr[2] = {2,1};
return A( arr );
}

int main()
{
A a = foo();
int* arr = a.getArr();

cout << arr[0] << endl; // This is not ambigous, since arr has
actually gone out of scope, am i right?
return 0;
}
Would you like to answer this question?
Sign up for a free account, or Login (if you're already a member).
Kai-Uwe Bux's Avatar
Kai-Uwe Bux
Guest
n/a Posts
July 4th, 2008
12:45 PM
#2

Re: Local array scope
D. Susman wrote:
Quote:
Originally Posted by
Hi,
>
When the method "foo" ends, shouldn't the arr[2] array be gone (due to
scope termination) and the pointer in class A be invalid?


Yes.
Quote:
Originally Posted by
However, when I run the program, I get "2".


You dereference an invalid pointer. Anything can happen, including a value
of 2.
Quote:
Originally Posted by
It seems to that I get this result by luck; in further executions, I may
get some other value. Am i right?


Yes.
Quote:
Originally Posted by
class A
{
public:
A( int* ptr ){ arr = ptr; }
int* getArr(){ return arr; }
private:
int* arr;
};
>
A foo( )
{
int arr[2] = {2,1};
return A( arr );
}
>
int main()
{
A a = foo();
int* arr = a.getArr();
>
cout << arr[0] << endl; // This is not ambigous, since arr has
actually gone out of scope, am i right?


"Ambiguous" ????

It is undefined behavior. That's all.
Quote:
Originally Posted by
return 0;
}



Best

Kai-Uwe Bux

 
Not the answer you were looking for? Post your question . . .
182,081 Experts ready to help you find a solution.
Sign up for a free account, or Login (if you're already a member).

  • Didn't find the answer you were looking for?
    Post Your Question
  • Top Community Contributors