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

时间:2015-04-26 06:17:55

标签: c++ arrays pointers pointer-to-array

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

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

通常,您不希望“返回”指向数组的指针。 外部功能中“arr”的类型是什么? 无论如何,下标符号是有效的,代码中的其他内容不是。

相关问题