0

I'm currently learning C++ and wrote an Array Reverse Function for learning purposes only.

Everything works fine. But if i want to write back my value from my stack into my array.. it fails.

#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;
}

This creates following output:

5
4
3
2
1
This should be 5: 1
Markus
  • 41
  • 7
  • Remove `register`, it doesn't do anything and has been obsolete for decades. A list of good modern books is [here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Nov 20 '17 at 12:50

2 Answers2

0

With the statement

a = &stack.top();

you have two problems:

  1. You assign to a local variable. That assignment will not outlive the life-time of the variable, which is until the function returns.

  2. You make the variable point to data that will no longer exist once you pop the element.

The solution to both of these issues is to save the value of a into a temporary variable that you use for the first loop. Then you can use a in the second loop much like you do in the first loop currently, and assign to its dereferenced value (like e.g. *a++ = stack.top()).


On an unrelated note, the register keyword has been deprecated since C++11 and will be removed in C++17. It will most certainly not do anything.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thank you for your reply! This means, that I've created an bad pointer, right? And I need do define an `int tmp = *a` or how should I implement the tmp variable? And do I need the `a++` in my loop when I use `*a++ = stack.top();` ? – Markus Nov 20 '17 at 13:18
0

I just solved the problem.

  • *arrayin this case is always pointing to the first item in array -> array[0]
  • I don't need array++, because i calculate it with *(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();
    }
    

    }

Markus
  • 41
  • 7