【问题标题】:C++ Write Stack Value to Array-Pointer / (Call by Ref-Function)C++ 将堆栈值写入数组指针/(通过 Ref-Function 调用)
【发布时间】: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。

标签: c++ arrays pointers stack


【解决方案1】:

附言

a = &stack.top();

你有两个问题:

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

  2. 使变量指向一旦弹出元素将不再存在的数据。

解决这两个问题的方法是将a 的值保存到您用于第一个循环的临时变量中。然后你可以在第二个循环中使用a,就像你在当前第一个循环中所做的那样,并分配给它的取消引用值(例如*a++ = stack.top())。


在不相关的注释中,register 关键字自 C++11 以来已被弃用,并将在 C++17 中删除。它肯定不会做任何事情。

【讨论】:

  • 感谢您的回复!这意味着,我创建了一个错误的指针,对吗?我需要定义一个int tmp = *a 或者我应该如何实现 tmp 变量?当我使用 *a++ = stack.top(); 时,我的循环中是否需要 a++ ?
【解决方案2】:

我刚刚解决了这个问题。

  • *array在这种情况下总是指向数组中的第一项 -> array[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();
    }
    

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 2014-02-23
    相关资源
    最近更新 更多