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.

JOH
  • 61
  • 1
  • 1
  • 7
  • 4
    `sizeof(array)` does not do what you think it does. – drescherjm Oct 30 '14 at 22:30
  • 2
    have a look at this answer http://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c – Hagai Oct 30 '14 at 22:54
  • 2
    If it is at-all an option, I would gut the source and just use: [**`std::reverse`**](http://en.cppreference.com/w/cpp/algorithm/reverse) from `main()`. – WhozCraig Oct 30 '14 at 23:32

1 Answers1

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.

DigitalEye
  • 1,456
  • 3
  • 17
  • 26
  • 1
    In case you're wondering, -858993460 = 0xCCCCCCCC, a common value used to fill the stack when a program is compiled in debug mode. – rcgldr Oct 31 '14 at 01:57