Connecting Tech Pros Worldwide Help | Site Map

Local array scope

 
LinkBack Thread Tools Search this Thread
  #1  
Old July 4th, 2008, 12:35 PM
D. Susman
Guest
 
Posts: n/a
Default Local array scope

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, 12:45 PM
Kai-Uwe Bux
Guest
 
Posts: n/a
Default 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
 

Bookmarks

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Popular Articles

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 220,840 network members.