0

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

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

2 回答 2

2

您忘记i在函数中递增DynStrStk::nodeStrings。因此,你所有的任务都是arr[0]

于 2015-04-26T06:30:06.833 回答
0

通常,您不想“返回”指向数组的指针。外部函数中“arr”的类型是什么?无论如何,下标符号是有效的,你的代码中的其他东西不是。

于 2015-04-26T06:25:10.117 回答