• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 202
  • Last Modified:

Creating an array in runtime

Dear Experts,
If this is possible (creating an unspecified array and size during runtime), including the memory allocation part, can you provide me a code example please?
I'm using C++. Thank you very much.

1 Solution
Jaime OlivaresCommented:
Sure you can.
In standard C++ you can use the vector template:

#include <vector>
vector <yourdatatype> array;

where yourdatatype could be a fundamental type like 'float' or a user-define class type.

In Visual C++, you can use CArray:

#include <afxtempl.h>
CArray <yourdatatype, yourdatatype> array;

you can use both as a standard C array, by example:

float a = array[0];

But you have more functionality than standard C arrays, including the possibility to grow array at runtime.
If array size is unknown at compile time, but known and fixed at runtime you can allocate an array like this:

int* pMyIntegerArray = new int[nSize];

where nSize is initialized at runtime to some fixed value. Don't forget to

delete pMyIntegerArray;

to make everyone happy... :-)
I recommend using vector<> or CArray type instead of using new[], since it will automatically clean up the memory.

To add to jaime_olivares's comment, if you use vector<> type, you can either initialize the vector with zero length, or initialize it with a specific size at runtime.

vector <yourdatatype> array(MySizeOfArray);

If you initialize it with no size value, then you can use the push_back function to make it grow as you need it.

vector <yourdatatype> array;
sunshine8888Author Commented:
Thank you for all the answers. I really appreciate it.

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now