Advertisement

02.12.2007 at 05:00AM PST, ID: 22159026
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

Returning arrays from functions in C++. Variable scope issuse.

Tags: array, return, function
Hello.

I am a Java developer transfering my skills over to C++. I am using C++ at University for a module dealing with OpenGL. I have used some OpenGL with C. I have been reasonably successfull in recreating things I have created in Java to C++ though I appreciate how clean Java is by comparrison.

One of the issues I am having some issues with is array pointer scope. In Java I can return an array from a method. I have tried to do the same thing in C++ but it does not seem to be working correctly when I run the debugger. I know that the other C++ way of doing things is to supply the method a pointer to an array and have the method simply populate it. I have not had problems when it has come to returning an object reference from a method. It seems my problems are just with arrays. It seems the array may be going out of scope when the method returns. I know that the new keword is used to create things in the memory heap and that items created in this mannor need to be explicitly destroyed (no garbage collection).

Can anyone give me some pointers for dealing with C++ arrays and issues relating to variable scope. I know that an array is equivelant to a pointer and that there is no protection to stop navigation beyond the bounds of the array. Can an object method return an array or will it only work if the array is created outside the method and passed as an argument?

Any help would be appreciated.

Carl
Start your free trial to view this solution
Question Stats
Zone: Programming
Question Asked By: carljokl
Solution Provided By: Infinity08
Participating Experts: 5
Solution Grade: A
Views: 210
Translate:
Loading Advertisement...
02.12.2007 at 05:30AM PST, ID: 18514623

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.12.2007 at 05:58AM PST, ID: 18514808

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.12.2007 at 05:59AM PST, ID: 18514809

Rank: Genius

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.12.2007 at 06:01AM PST, ID: 18514826

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.12.2007 at 10:21AM PST, ID: 18516960

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.13.2007 at 12:17AM PST, ID: 18521242

Rank: Wizard

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.13.2007 at 01:47AM PST, ID: 18521538

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
02.17.2007 at 11:26AM PST, ID: 18556154

All comments and solutions are available to Premium Service Members only.

Start your 7 day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
 
Loading Advertisement...
Microsoft
  • Internet Protocols
  • Applications
  • Development
  • OS
  • Hardware
  • Windows Security
Apple
  • Operating Systems
  • Hardware
  • Programming
  • Networking
  • Software
Internet
  • Search Engines
  • File Sharing
  • WebTrends / Stats
  • Spy / Ad Blockers
  • Web Browsers
  • New Net Users
  • Web Development
  • Chat / IM
  • Anti Spam
  • Web Servers
  • Anti-Virus
  • Email Clients
Gamers
  • Tips
  • Online / MMORPG
  • Puzzle
  • Emulators
  • Action / Adventure
  • Role Playing
  • Consoles
  • Game Programming
  • Strategy
  • Sports
  • Misc
  • Computer Games
Digital Living
  • Hardware
  • New Net Users
  • New Users
  • Software
  • Digital Music
  • Gaming World
  • Home Security
  • Apple
  • Networking Hardware
Virus & Spyware
  • Vulnerabilities
  • IDS
  • Encryption
  • Anti-Virus
  • Operating Systems Security
  • Software Firewalls
  • WebApplications
  • Cell Phones
  • Operating Systems
  • Internet
  • Hardware Firewalls
Hardware
  • Handhelds / PDAs
  • Displays / Monitors
  • Components
  • Networking Hardware
  • Peripherals
  • Laptops/Notebooks
  • Storage
  • Servers
  • Desktops
  • New Users
  • Misc
  • Apple
Software
  • System Utilities
  • Industry Specific
  • Network Management
  • Photos / Graphics
  • Page Layout
  • VMWare
  • Misc
  • Web Development
  • OS
  • CYGWIN
  • Voice Recognition
  • Message Queue
  • Quality Assurance
  • Security
  • Firewalls
  • MultiMedia Applications
  • Development
  • Database
  • Office / Productivity
  • Business Management
  • OS/2 Apps
  • Server Software
  • Internet / Email
ITPro
  • OS
  • Storage
  • Encryption
  • Operating Systems Security
  • Apple Hardware
  • Laptops & Notebooks
  • Servers
  • Networking Hardware
  • Peripherals
  • Devices
  • Displays / Monitors
  • WebTrends / Stats
  • Search Engines
  • Firewalls
  • WebApplications
  • IDS
  • Vulnerabilities
  • Email Clients
  • File Sharing
  • Spy / Ad Blockers
  • Web Browsers
  • Web Servers
  • Networking
  • Anti-Virus
  • Chat / IM
  • Anti Spam
Developer
  • Web Servers
  • Web Browsers
  • Game Programming
  • Dev Tools
  • Industry Specific
  • Office / Productivity
  • Database
  • CYGWIN
  • Web Development
  • Search Engines
  • File Sharing
  • WebTrends / Stats
  • Programming
  • Content Management
  • Application Servers
  • Protocols
Storage
  • Removable Backup Media
  • Storage Technology
  • Servers
  • Grid
  • Remote Access
  • Backup / Restore
  • Misc
  • Hard Drives
OS
  • Miscellaneous
  • Security
  • Development
  • Linux
  • VMWare
  • MainFrame OS
  • Unix
  • Apple
  • OS / 2
  • AS / 400
  • BeOS
  • Microsoft
  • VMS / OpenVMS
Database
  • Oracle
  • Miscellaneous
  • MySQL
  • Software
  • Sybase
  • Contact Management
  • PostgreSQL
  • Data Manipulation
  • Clarion
  • InterSystems Cache
  • Siebel
  • MUMPS
  • OLAP
  • SQLBase
  • SAS
  • GIS & GPS
  • 4GL
  • Berkeley DB
  • DB2
  • Informix
  • Interbase / Firebird
  • FoxPro
  • Reporting
  • LDAP
  • Filemaker Pro
  • MS SQL Server
  • dBase
  • MS Access
Security
  • Misc
  • Web Browsers
  • Software Firewalls
  • Operating Systems Security
  • File Sharing
  • Spy / Ad Blockers
  • Vulnerabilities
  • WebApplications
  • IDS
  • Anti-Virus
  • Encryption
  • Anti Spam
  • Email Clients
  • VPN
  • Chat / IM
Programming
  • Editors IDEs
  • Installation
  • Handhelds / PDAs
  • Multimedia Programming
  • System / Kernel
  • Algorithms
  • Game
  • Signal Processing
  • Project Management
  • Open Source
  • Database
  • Misc
  • Languages
  • Processor Platforms
  • Theory
Web Development
  • Scripting
  • Blogs
  • Web Servers
  • Software
  • Search Engines
  • Web Graphics
  • Images
  • Internet Marketing
  • Images and Photos
  • Components
  • Document Imaging
  • Web Languages/Standards
  • Illustration
  • WebApplications
  • Fonts
  • WebTrends / Stats
  • Authoring
  • Digital Camera Software
  • Miscellaneous
Networking
  • Protocols
  • Apple Networking
  • Network Management
  • Message Queue
  • Application Servers
  • Content Management
  • File Servers
  • Email Servers
  • Misc
  • Java Editors & IDEs
  • Wireless
  • Networking Hardware
  • Backup / Restore
  • System Utilities
  • ISPs & Hosting
  • Web Servers
  • Storage Technology
  • Removable Backup Media
  • Servers
  • Broadband
  • Grid
  • OS / 2
  • Novell Netware
  • Unix Networking
  • Windows Networking
  • Security
  • Telecommunications
  • Operating Systems
  • Linux Networking
Other
  • Community Advisor
  • Lounge
  • Community Support
  • New Net Users
  • Philosophy / Religion
  • Math / Science
  • Miscellaneous
  • URLs
  • Expert Lounge
  • Politics
  • Puzzles / Riddles
Community Support
  • Suggestions
  • New to EE
  • New Topics
  • Community Advisor
  • CleanUp
  • Announcements
  • General
  • Feedback
  • Input
  • EE Bugs
 
02.12.2007 at 05:30AM PST, ID: 18514623
"Can an object method return an array or will it only work if the array is created outside the method and passed as an argument? "

Yes.  Arrays created inside the method body will be out of scope when they reach the end, and so possibly over written.

You said yourself that it is common practice to pass a pointer into the method, this is the way it should be done.  

Pointers and references are tottaly different, I would look up these differences.

Andrew
 
02.12.2007 at 05:58AM PST, ID: 18514808

Rank: Sage

When you return an array, you actually return a pointer to an array. On the whole you need to allocate storage for that array as well as populating it and the calling code needs to know if it needs to free up the memory allocated to the array or not, which means documentation. Yuck.

"Arrays are evil." - see the C++ FAQ.

The C/C++ array is even more primitive than Java's and requires you to manage memory.

But... if you return a vector, memory management is done for you. The C++ vector is analogous to java.util.Vector.
 
02.12.2007 at 05:59AM PST, ID: 18514809

Rank: Genius

>> though I appreciate how clean Java is by comparrison.
C++ requires a bit more effort to get things done correctly. Especially pointers (as you noticed) can cause a lot of problems if you don't know what's going on exactly. That's what I'll try to clarify a bit in this reply.

>> One of the issues I am having some issues with is array pointer scope.
An array created like this :

    int array[10];

will be on the stack. The stack is the space in memory used for local variables and function parameters. Variables on this stack go out of scope once the block where they were declared ends. So, if you declare an array in a function, it will not be available any more when you return from that function.

An array created like this :

    int *array = new int[10];

will be on the heap. The heap is the space in memory for dynamically allocated data blocks. Variables on the heap will stay there untill you explicitly delete them :

    delete [] array;

The danger here of course is : if you don't delete them, they still take up memory, and you've got a memory leak. So, always clean up your dynamically allocated data from the moment you don't need it any more.

>> In Java I can return an array from a method. I have tried to do the same thing in C++ but it does not seem to be working correctly when I run the debugger.

I suspect you returned an array that was located on the stack and not on the heap.

>> I know that the other C++ way of doing things is to supply the method a pointer to an array and have the method simply populate it.

That's a very common way of doing it. It's cleaner, and it allows you to return something else from the function (like a result code). However, it's not less valid to return the array, if that fits your code better.

In both cases, you have to make sure that the array is still in scope when you're using it.

I'll give an example of both of the discussed options. First passing as argument :

    void fun(int *arr, int len) {
      for (int i = 0; i < len; i++) arr[i] = i;
    }

    int array[10] = { 0 };
    fun(array, 10);

And returning from the function :

    int *fun(int len) {
      int *tmp = new int[len];
      for (int i = 0; i < len; i++) tmp[i] = i;
      return tmp;
    }

    int *array = fun(10);

Note that I didn't add any error checks for clarity.

>> Can anyone give me some pointers for dealing with C++ arrays and issues relating to variable scope.
I hope I did that ... if something is still not clear, then please ask.

>> I know that an array is equivelant to a pointer
This is only true in a way : you can treat an array as a pointer, and vice versa, but they're two different concepts.
An array is a number of items of the same type that are stored consecutively in memory (on the stack).
A pointer is basically just an address in memory - it points to a location in memory. By giving a type to a pointer (for example int* or pointer to int), you tell the compiler that the data at that address should be interpreted as an int. You can use that same pointer to retrieve the data after that first int, and also interprete it as an int, and so on. This way, you emulate an array (on the heap), that is accessed through a pointer.

I know this is confusing, but it is something that you have to understand if you want to be a successful C++ coder. Please ask for clarification wherever I wasn't clear enough.

>> and that there is no protection to stop navigation beyond the bounds of the array.
That's indeed something you have to keep track of yourself, and is a cause of a lot of common mistakes and bugs.

>> Can an object method return an array or will it only work if the array is created outside the method and passed as an argument?
You can return an array from an object method the same way you can for a function. They behave exactly the same.
Accepted Solution
 
02.12.2007 at 06:01AM PST, ID: 18514826

Rank: Sage

It is as easy as....

vector<int> f() {
   vector<int> v(3);
   v[0] = 1;v[1] = 2;v[2] = 3;
   return v;
}
 
02.12.2007 at 10:21AM PST, ID: 18516960
the function below will return an array of double values,

double* myfunction(void)
{
  double* d=new double[3];  // can be static or dynamic
  d[0]=1;
  d[1]=2;
  d[2]=3;
 
  return d;

}


int main
{
  double* myvar=myfunction();
  for(int i=0;i<3;i++)
     cout<<*(myvar+i)<<endl;

  delete[] myvar;

  return 0;

}

The logic is same with the objects

class CExample
{
   int x,y;
  //constructors and other stuff
};


CExample* returnObjArr()
{
   CExample* pCEx=new CExample[2];
   pCEx[0].x=2;pCEx[0].y=3;
   pCEx[1].x=1;pCEx[1].y=0;

  return pCEx;
}

int main
{

   CExample* pC=returnObjArr();
   for(int i=0;i<2;i++)
    cout<<(pC+i)->x<<endl;    //should print 2 and 1

   delete[] pC;

   return 0;

}


   

 
02.13.2007 at 12:17AM PST, ID: 18521242

Rank: Wizard

You have already received sufficient good advice, but strictly speaking, a function cannot return an array.  A function can return a pointer or a vector, as my colleagues have shown, but neither of these is the same as an array.  So technically, the answer to the question "Can an object method return an array?" is "no."
 
02.13.2007 at 01:47AM PST, ID: 18521538

Rank: Sage

> "no."

Agreed, unless you wrap the array in a struct, which is what http://www.boost.org/boost/array.hpp does. You can return (say) boost::array<int,32>, if you want to return a fixed size 32 element managed array of integers. This is more efficient than returning a std::vector<int>, but less flexible. A nice feature of boost:array<> is that wrapping an array allows you to initialise in the same way that you do for a primitive array, if your compiler is standards-compliant - see Josutis's design rationale at http://www.boost.org/doc/html/array/rationale.html.

Beware that returning boost:array<> suffers the overhead of copy semantics, but it is still more efficient than returning a std::vector<>, if your array is a fixed size. Macroland's pointer approach is more efficient, but requires the client code to take responsibility for deleting the array afterwards. Don't look at std::auto_ptr<> as a solution for returning pointers to arrays in a managed way, for reasons stated at http://www.gotw.ca/gotw/042.htm.

So C++ sounds pretty awful, don't it, when Java apparently does the right thing? Well all of this complexity is the price of flexibility. Infinity08 explained nicely the fact that C/C++ programmers are allowed to choose stack vs heap. Choice allows C/C++ programs to be more efficient than Java, but it also allows us to mess up more!
 
02.17.2007 at 11:26AM PST, ID: 18556154
I wonder if learning to cope with C++ will also make me more of a Man. Who knows. Anyway I have found out what I need to know.
 
 
20080236-EE-VQP-29