AMAN SANGAL AMAN SANGAL - 1 month ago 6
C++ Question

How to declare multiple arrays with similar name in a for loop?

I want to declare 32 1d arrays with name efficiency_module_cmp_%d_x, %d goes from 1 to 16 and efficiency_module_cmp_%d_y, %d goes from 1 to 16.
I am using the following code to do this but this is not working. what is wrong with this:

char array_name[100];
char array_name1[100];


for ( int i=0; i<16;i++)
{

sprintf(array_name,"efficiency_module_cmp_%d_x",i+1);
float array_name[n] ;
sprintf(array_name1,"efficiency_module_cmp_%d_y",i+1);
float array_name1[n] ;

}


Suggest a possible solution.

Answer Source

You cannot create names of objects at run-time (C++ is statically typed). Instead, you can make an vector (or any other container) of arrays, and push your arrays to the back of the container like so:

#include <vector>
int main()
{
    std::vector<char*> vectorOfArrays;
    for (int i = 0; i < 16; i++) {
        vectorOfArrays.push_back(new char[10]);
    }
    return 0;
}

Then you can access one of your arrays like this: vectorOfArrays[3];