I have created a function that returns a pointer to an array of strings. The function should traverse a linked list and it should assign the data from each node into an array of string. Here is my function:
//function to traverse every node in the list
string *DynStrStk::nodeStrings(int count)
{
StackNode *nodePtr = nullptr;
StackNode *nextNode = nullptr;
int i = 0;
//Position nodePtr at the top of the stack
nodePtr = top;
string *arr = new string[count];
//Traverse the list and delete each node
while(nodePtr != nullptr && i < count)
{
nextNode = nodePtr->next;
arr[i] = nodePtr->newString;
nodePtr = nextNode;
cout << "test1: " << arr[i] << endl;
}
return arr;
}
i want to use that pointer to the array returned by the function above, and i want to assign it to a new array in a different function where it will test each subscript in that array for a condition.
i am having trouble accessing the new array and i can't even print out the string in each new array element.
arr = stringStk.nodeStrings(count);
cout << "pointer to arr of str: " << *arr << endl;
for(int i = 0; i < count; i++)
{
cout << "test2: " << arr[i] << endl;
}
this is my output after calling both functions:
test1: rotor
test1: rotator
test1: racecar
test1: racecar
pointer to arr of str: racecar //this test tells me i can get to array
test2: racecar
test2:
test2:
test2:
this is my expected output
test1: rotor
test1: rotator
test1: racecar
test1: racecar
pointer to arr of str: racecar
test2: racecar
test2: racecar
test2: rotator
test2: rotor
what am i doing wrong and how can i access each element in the new array from the second function??????
thanks!!!!
here is the second function using the pointer to the array:
int createStack(fstream &normFile, ostream &outFile)
{
string catchNewString;
string testString, revString;
string *arr;
int count = 0; //counts the number of items in the stack
DynStrStk stringStk;
while(getline(normFile,catchNewString)) // read and push to stack
{
stringStk.push(catchNewString); // push to stack
//tracer rounds
outFile << catchNewString << endl;
count++;
}
arr = stringStk.nodeStrings(count);
cout << "pointer to arr of str: " << *arr << endl;
for(int i = 0; i < count; i++)
{
cout << "test2: " << (arr[i]) << endl;
}
return count;
}
You forgot to increment i
in the function DynStrStk::nodeStrings
. Therefore all your assignments are to arr[0]
.