Question

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

Asked by: carljokl

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

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-02-12 at 05:00:52ID22159026
Tags

array

,

return

,

function

Topics

OpenGL Graphics & Game Programming

,

C++ Programming Language

Participating Experts
5
Points
500
Comments
8

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. OpenGL Texture Mapping
    Hey folks, I need a piece of Delphi4-code that makes use of plain OpenGL-syntax and does the following: A rectangle with a texture on it (loaded from a BMP) turning e.g. around the z-axis with a background image (also loaded from a BMP) behind the scene. The main problem is ...
  2. OpenGl
    ONLY OPENGL CODE WILL BE ACCEPTED!!! I need a sample program of a bitmap that looks like a ball thrown up. When gravity overpowers the throw the ball should fall down. Please do not not use glut.h use only gl.h or glu.h I will assign extra 50 points if the program works!!!
  3. Good Programming Skills
    I was wondering if someone could Comment on your basic programming skills to write standardized code to make testing and documentation easier. Thanks!
  4. Destroy objects
    Hi I'm using objects of a class I wrote and I want to destroy the objects when I finish using them to free memory. How can I do this? What is the code that usually goes into destructors? An example would be very helpful. Thanks, gabi
  5. export maya object to opengl
    Well, I'm new to both maya and opengl. I just want to learn how to expert an object from maya to opengl. That's all. Thanks.
  6. OpenGL and DoModal
    Hello !! I'm writing this quite big application, everything goes smooth but there is this one thing, I have no idea how to handle it. Beside non-modal dialogs gathered in property sheet there is window with opengl in it. The problem is, when I want a dialog to go modal (for ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Andrewm1986Posted on 2007-02-12 at 05:30:55ID: 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

 

by: rstaveleyPosted on 2007-02-12 at 05:58:48ID: 18514808

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.

 

by: Infinity08Posted on 2007-02-12 at 05:59:14ID: 18514809

>> 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.

 

by: rstaveleyPosted on 2007-02-12 at 06:01:05ID: 18514826

It is as easy as....

vector<int> f() {
   vector<int> v(3);
   v[0] = 1;v[1] = 2;v[2] = 3;
   return v;
}

 

by: MacroLandPosted on 2007-02-12 at 10:21:36ID: 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;

}


   

 

by: efnPosted on 2007-02-13 at 00:17:48ID: 18521242

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."

 

by: rstaveleyPosted on 2007-02-13 at 01:47:33ID: 18521538

> "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!

 

by: carljoklPosted on 2007-02-17 at 11:26:55ID: 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.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...