0

I have successfully reversed a 1-D array but when I cout the contents, it prints out the contents then bunch of other numbers.

4
3
2
1
-858993460
-858993460
4
-858993460
-1021245226
12384668
3697177
1
14484784
14501672
-1021245434
0
Press any key to continue . . .

I can't tell why it's printing out those extra numbers. Below is my source code:

#include <iostream>
#include <array>

using namespace std;

void flipRow(int array[], int row) {
    int temp;
    for (int i = 0; i < sizeof(array)/2; i++) {
        //cout << "Hi" << endl;
        temp = array[i];
        array[i] = array[row-1];
        array[row-1] = temp;
        row--;
    }
}

int main() {

    const int ROW = 4;

    int array[ROW] = { 1, 2, 3, 4 };
    flipRow(array, ROW);

    for (int i = 0; i < sizeof(array); i++) {
        cout << array[i] << endl;
    }

    system("pause");
    return 0;
}

Are those addresses? Can someone tell why it's printing them out? Thank you.

3
  • 4
    sizeof(array) does not do what you think it does. Commented Oct 30, 2014 at 22:30
  • 2
    have a look at this answer stackoverflow.com/questions/37538/… Commented Oct 30, 2014 at 22:54
  • 2
    If it is at-all an option, I would gut the source and just use: std::reverse from main(). Commented Oct 30, 2014 at 23:32

1 Answer 1

1

Modify your for loop in main so the condition part of it becomes i < ROW and modify the for loop in flipRow so the condition part there reads i < row/2. sizeof operator returns the size of your array in bytes. You have four elements in your array and they are of type integer, which on your platform is 4 bytes, so your call to sizeof is returning 16.

Sign up to request clarification or add additional context in comments.

1 Comment

In case you're wondering, -858993460 = 0xCCCCCCCC, a common value used to fill the stack when a program is compiled in debug mode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.