gpt4 book ai didi

c++ - 如何使用下标访问作为函数指针返回的数组?

转载 作者:行者123 更新时间:2023-11-28 02:28:00 25 4
gpt4 key购买 nike

我创建了一个返回指向字符串数组的指针的函数。该函数应该遍历一个链表,并将每个节点的数据分配到一个字符串数组中。这是我的功能:

//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

我做错了什么以及如何从第二个函数访问新数组中的每个元素?????

谢谢!!!!

这是使用数组指针的第二个函数:

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;
}

最佳答案

您忘记在函数 DynStrStk::nodeStrings 中增加 i。因此,您所有的作业都是 arr[0]

关于c++ - 如何使用下标访问作为函数指针返回的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29874438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com