Connecting Tech Pros Worldwide Help | Site Map

Local array scope

  #1  
Old July 4th, 2008, 01:35 PM
D. Susman
Guest
 
Posts: n/a
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;
}
  #2  
Old July 4th, 2008, 01:45 PM
Kai-Uwe Bux
Guest
 
Posts: n/a

re: Local array scope


D. Susman wrote:
Quote:
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:
However, when I run the program, I get "2".
You dereference an invalid pointer. Anything can happen, including a value
of 2.
Quote:
It seems to that I get this result by luck; in further executions, I may
get some other value. Am i right?
Yes.
Quote:
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:
return 0;
}

Best

Kai-Uwe Bux
Closed Thread


Similar Threads
Thread Thread Starter Forum Replies Last Post
variable scope problem ray answers 2 October 9th, 2008 04:15 AM
Local structs Christian Christmann answers 6 May 25th, 2006 05:55 AM
Try/Catch Array Scope Problem Matt Harvey answers 4 April 25th, 2006 08:35 PM
how to create an Array with parametrized name? nobody answers 22 July 20th, 2005 01:47 PM