Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array lifetime

Status
Not open for further replies.

minoad

Programmer
Mar 28, 2001
138
US
How can i create an array within a funtion or a class and have it available to the rest of the code in the entire project?

Micah A. Norman
 
The only way: allocate an array in the function then return a pointer to it, for example:
Code:
int* AllocArrayAndOthers(int n, /* another parms */)
{
...
  int* pmyarray;
...
  p = new int[n];
...
  return p;
}
Don't forget to deallocate this array later:
Code:
...
int* p = AllocArrayAndOthers(......);
...
delete [] p;
...
[code]
Of course, you may wrap this pointer into the proper class (for safety) and return this class object, but it's the other story. The key point here: only dynamic allocation creates long-lived objects on the fly...
 
You could also make it static.
Code:
class CBlah
{
public:
    ...
    static const std::string*  ReturnStringArray();
};

const std::string*
CBlah::ReturnStringArray()
{
    static const std::string str[] = { "First",
                                       "Second",
                                       "Third" };
    return str;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top