Maxwell.Winslow Maxwell.Winslow - 3 months ago 5
C++ Question

Cant get arrays to keep value in class

When I use the object function

set_and_make_variable
I send it a name and value which both work correctly. However then when I go to use show
current_variables
it acts like I never set the values for both
integers
, and
integers_names
. I thought you could modify the variables arrays from the functions associated with the class without references or pointers.

Am I not correct?

void reset_name(string *variable_names)
{
for (int i = 0; i < 100; i++)
{
variable_names[i] = "";
}
}
void reset_int_value(int *variable_value)
{
for (int i = 0; i < 100; i++)
{
variable_value[i] = 0;
}
}
int find_next(string variable_names[100])
{
for (int i = 0; i < 100; i++)
{
if (variable_names[i] == "")
{
return i;
}
}
}


//*****************************************************************
class variables_integers
{
public:
string integer_names[100];
int integers[100];

variables_integers(void);
void set_and_make_variable(string, int);
void show_current_variables(void);

};

variables_integers::variables_integers(void)
{
reset_int_value(integers);
reset_name(integer_names);
}

void variables_integers::show_current_variables(void)
{
cout << "INTEGERS:" << endl;

for (int i = 0; i < (find_next(integer_names)); i++)
{
cout << integer_names[i] << " = " << integers[i] << endl;
}
}

void variables_integers::set_and_make_variable(string name, int value)
{
cout << name << " " << value << endl;
cout << find_next(integer_names) << endl;
integers[find_next(integer_names)] = value;
integer_names[find_next(integer_names)] = name;
}


//*** added code ******
bool operations_and_declerations(string parsed_input[3000], variables variable)
{
if (parsed_input[0] == "int")
{
if (parsed_input[2] == "=")
{
variable.integers.set_and_make_variable(parsed_input[1], atoi(parsed_input[3].c_str()));
}
return true;
}
else if (parsed_input[0] == "string")
{
return true;
}
//else if (parsed_input[0] ==)
else
{
return false;
}
}

Answer

In operations_and_declerations(), you sent your variables parameter by value. Hence, the function created a local copy, and only modified that local copy.

You can fix the problem by sending it the parameter by reference. Just modify the function name to: bool operations_and_declerations(string parsed_input[3000], variables & variable)

Comments