如何使用下标访问从函数作为指针返回的数组

how do i access an array returned as a pointer from a function using a subscript?

本文关键字:指针 返回 数组 函数 何使用 下标 访问      更新时间:2023-10-16

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

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

通常,您不希望"返回"指向数组的指针。外部函数中的"arr"类型是什么?无论如何,下标表示法是有效的,代码中的其他内容不是。