Take the 2-minute tour ×

I want to create a for loop that will fill a bunch of arrays with data in c++. Now to save space and in the future once more arrays are added which they will, I have the for loop. Each array for demonstration purposes is called Array# (# being a number) The point of the for loop would be to set a constant with maximum arrays, then cycle through each array filling by appending i to the end of the Array name.

For example in pseudo code:

for (i = 1; i < numberofarrays; i++)  
{ fill (Array & i) with ("Array" & i & "-default.txt")}
share|improve this question
So... you want an array of arrays? –  DarkDust Aug 9 '13 at 13:04
no i want to only be able to change 'numberofarrays' and it will fill all arrays that are arranged "Array" + number, finding the file is easy i know how to do that. –  Callum Hutchinson Aug 9 '13 at 13:08
You can't do it this way in C++. Use a container. –  Joe Aug 9 '13 at 13:08
Duplicate of stackoverflow.com/questions/18125041/… –  dunc123 Aug 9 '13 at 13:10

2 Answers 2

up vote 8 down vote accepted

It is impossible to generate Variable Names by any type of code.
(Meaning it is impossible to generate dynamic variable names on Runtime or on Compiletime)

The best solution possible would be a array of arrays:

int Arrays[][];

Calling Arrays[0] would give you the first array.

If you want to determine the number of arrays during Runtime you need to use pointers!

That would look like that:

(int[])* Arrays = new (int[])[numberofarrays];

Accessing the arrays in the array would work the same!

An alternative would be using the container vector from std.

The code would the look like this:


// More includes

// Optional
using namespace std;

// Somewhere in your code
vector<vector<int>> Arrays;

You still would acces the elements by using your standard array method (Arrays[15][78] e.g.)

share|improve this answer
ok thank you I will try these methods out and see what way will work for me –  Callum Hutchinson Aug 9 '13 at 13:14

You don't really need the name. You can use an std::vector of arrays. This will not work out of the box, see Correct way to work with vector of arrays

Another approach would be to have an std::map of arrays. You could have the name as the key, if that is what you really want. You will still have to use the same workaround as before to have an array as a value. See Character Array as a value in C++ map for example.

share|improve this answer

Your Answer


