如何使用下标访问从函数作为指针返回的数组
how do i access an array returned as a pointer from a function using a subscript?
我创建了一个函数,该函数返回指向字符串数组的指针。该函数应遍历链表,并应将每个节点的数据分配到字符串数组中。这是我的函数:
//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"类型是什么?无论如何,下标表示法是有效的,代码中的其他内容不是。
相关文章:
- 在 const 函数中通过引用和指针返回之间的区别
- 指向 std::unrodered_map 中元素的指针返回'Read access violation'
- 为什么要为指针返回类型返回一系列字符?
- Visual C 运行时:Malloc将指针返回到已经使用的内存(包含实际字符串)
- 将原始指针返回到智能指针
- 从函数中的指针返回对象,例如链接列表
- 将指针返回使用New创建的数组数组
- 查找并将指针返回向量中的对象
- 函数可以将指针返回其自己的类型
- 指针返回值的地址
- 为什么静态指针返回函数中有一个"静态"键?
- 从弱指针返回类型返回共享指针
- 如何将C++引用和指针返回转换为 C++/CLR
- 从指针返回对象时出现意外的析构函数调用
- 阵列指针返回垃圾
- (C )当在同一类中调用时,污点指针返回正确的值,而从MAIN调用时为0
- C 从指针返回到成员功能
- 在构造函数以外的任何其他位置访问相机时,我的相机指针返回 null
- 从取消引用的指针返回原始指针
- 指针返回