C ++将堆栈值写入数组指针/(通过Ref-Function调用)

时间:2017-11-20 12:37:34

标签: c++ arrays pointers stack

我目前正在学习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

2 个答案:

答案 0 :(得分:0)

声明

a = &stack.top();

你有两个问题:

  1. 您分配给本地变量。该赋值不会超过变量的生命周期,直到函数返回。

  2. 您可以将变量指向弹出元素后不再存在的数据。

  3. 解决这两个问题的方法是将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();
    }
    

    }