我目前正在学习C ++并编写了一个数组反向函数,仅用于学习目的。
一切正常。但是如果我想把我的堆栈中的值写回到我的数组中......那就失败了。
#include "iostream"
#include <stack>
using namespace std;
void reverseArray(int *a, int s) {
stack<int> stack;
register int i;
for (i = 0; i < s; i++) { // iterates from 0 to 5
stack.push(*a);
a++; // pointer adress + 4 byte
}
for (i = 0; i < s; i++) { // iterates from 0 to 5
a = &stack.top(); // this fails!!
printf("%i\n", *a); // Here ist the right output
stack.pop();
a++; // pointer adress + 4 byte
}
}
int main() {
const int SIZE = 5;
int array[SIZE] = {1, 2, 3, 4, 5};
reverseArray(&array[0], SIZE);
printf("This should be 5: %i\n", array[0]);
return 0;
}
这会创建以下输出:
5
4
3
2
1
This should be 5: 1
答案 0 :(得分:0)
声明
a = &stack.top();
你有两个问题:
您分配给本地变量。该赋值不会超过变量的生命周期,直到函数返回。
您可以将变量指向弹出元素后不再存在的数据。
解决这两个问题的方法是将a
的值保存到用于第一个循环的临时变量中。然后,您可以在第二个循环中使用a
,就像在当前第一个循环中一样,并分配到其解除引用的值(例如*a++ = stack.top()
)。
在一个不相关的说明中,自{+ 1}}关键字自C ++ 11以来已被弃用,并将在C ++ 17中删除。它绝对不会做任何事情。
答案 1 :(得分:0)
我刚解决了这个问题。
*array
始终指向数组中的第一项 - &gt;阵列[0] 我不需要array++
,因为我用*(array + i)
void reverse(int *array, const int s) {
stack<int> stack1;
for (int i = 0; i < s; i++) {
stack1.push(*(array + i));
}
for (int i = 0; i < s; i++) {
*(array + i) = stack1.top();
stack1.pop();
}
}