文字列の配列へのポインターを返す関数を作成しました。関数はリンクされたリストをトラバースし、各ノードからのデータを文字列の配列に割り当てる必要があります。これが私の機能です:
//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;
}
上記の関数によって返された配列へのそのポインターを使用したいのですが、それを別の関数の新しい配列に割り当てて、その配列内の各添字の条件をテストしたいと考えています。
新しい配列へのアクセスに問題があり、新しい配列要素ごとに文字列を出力することさえできません。
arr = stringStk.nodeStrings(count);
cout << "pointer to arr of str: " << *arr << endl;
for(int i = 0; i < count; i++)
{
cout << "test2: " << arr[i] << endl;
}
これは両方の関数を呼び出した後の私の出力です:
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:
これは私の期待される出力です
test1: rotor
test1: rotator
test1: racecar
test1: racecar
pointer to arr of str: racecar
test2: racecar
test2: racecar
test2: rotator
test2: rotor
私は何を間違っているのですか?また、2番目の関数から新しい配列の各要素にアクセスするにはどうすればよいですか????
ありがとう!!!!
配列へのポインターを使用する 2 番目の関数を次に示します。
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;
}