0

I would like to get some help with c++. Im trying to change the array name using value from variable. something like this:

global variables:

string array1[5][5];
string array2[5][5];

in a function:

string var;
if (option1) { var = "array1"; }
if (option2) { var = "array2"; }
var[1][1]="some data";

unfortunately this does not work. is there any way to manage the arrays like this?

1
  • 1
    Your var is a String, how can var[1][1] work? Commented Dec 2, 2015 at 3:22

3 Answers 3

2

Yes, you can use a pointer:

decltype(array1) *ptr{};

if ( option1 )       ptr = &array1;
else if ( option2 )  ptr = &array2;

if ( ptr )
    (*ptr)[1][1] = "some data";
Sign up to request clarification or add additional context in comments.

Comments

1

No, you can't. You should

string array1[5][5];
string array2[5][5];

string (*var)[5];
if (option1) { var = array1; }
if (option2) { var = array2; }
var[1][1]="some data";

Comments

1

No, there isn't.

You could use another level of array indexing:

string array[2][5][5];

int var;
if(option1) {var = 0;}
if(option2) {var = 1;}
array[var][1][1] = "some data";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.