【发布时间】:2018-05-03 16:25:45
【问题描述】:
我目前正在学习 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
【问题讨论】:
-
删除
register,它什么也没做,而且已经过时了几十年。好的现代书籍列表是here。