This is a snippet from a larger block of code. The print statements are included for testing.

Within 'main', if I ouput the 'cell_ptr' or 'params' pointers, it correctly returns pointer values but if I try to output an element from the params array, I get an '...illegal operation...' message.

Yet it works OK in the sub.
What am I doing wrong?

struct keys {
	string	*params;
	keys	*next;
};
keys	*cell_ptr = NULL;
void build_celldata()
{
	keys	*curr;
	char buffer[5];
	string cells[] = { "R0","" };
	for (int i=0; i<5; i++)
	{
		sprintf(buffer, "%d", i);
		string si = buffer;
		cells[1] = "celldata" +si+ "0";
		keys	*temp = new keys;
		temp->params	= cells;
		temp->next		= NULL;
		if (cell_ptr == NULL)
		{
			cell_ptr = temp;
			curr = cell_ptr;
// testing
cout << cell_ptr->params[0] << "=" << cell_ptr->params[1] << endl;
		}
		else
		{
			curr->next = temp;
			curr = curr->next;
//testing
cout << curr->params[0] << "=" << curr->params[1] << endl;
		}
	}
}

int main()
{
	build_celldata();
//testing
cout << cell_ptr->params[0] << "=" << cell_ptr->params[1] << endl;
	return 0;
}

params is a pointer to the cells array, but the cells array is destroyed when build_celldata returns.

Thanks, Narue.
Closely examining my code, I also realized that the 'cells' array pointer never changes, so the data was overwritten within the 'for' loop. Not exactly what I wanted.
I edited the code as shown, and now it works. :)

struct keys {
  string  params[2];
  keys    *next;
};
keys  *cell_ptr = NULL;
void build_celldata()
{
  keys  *curr;
  char  buffer[5];
  for (int i=0; i<5; i++)
  {
    sprintf(buffer, "%d", i);
    string si = buffer;

    // Build each 'params' array here.
    keys  *temp = new keys;
    temp->params[0] = "R0";
    temp->params[1] = "celldata" +si+ "0";
    temp->next      = NULL;

    if (cell_ptr == NULL)
    {
      cell_ptr = temp;
      curr = cell_ptr;
    }
    else
    {
      curr->next = temp;
      curr = curr->next;
    }
  }
}

int main()
{
  build_celldata();
//testing
cout << cell_ptr->params[0] << "=" << cell_ptr->params[1] << endl;
  return 0;
}
This article has been dead for over six months. Start a new discussion instead.