Connor Ronnoc
Connor Ronnoc

Reputation: 5

Why are the integers in the array negative after reversing the array and reversing back to the original array?

void reverseArray(int arrayLength, int sequence[]){
    int temparr[arrayLength];
    int *pointStart = sequence;
    int *pointEnd = sequence + arrayLength - 1;
    for(int i = 0; i < arrayLength; i++){
        temparr[i] = *pointEnd - i;  
    }
    for(int i = 0; i < arrayLength; i++){
        sequence[i] = temparr[i];
    }

}

void printArray(int arrayLength, int sequence[]){
    for(int i = 0; i < arrayLength; i++, sequence++){
        std::cout << *sequence << " ";
    }
    std::cout << "\n";
}




int main(int argc, char **argv) {
    const int num = 50;
    int arr[num]; 

    for (int i = 0; i < num; i++){
      arr[i] = i;
    }

    reverseArray(num, arr);
    std::cout << "Printing reverse array...\n";
    printArray(num, arr);
    reverseArray(num, arr);
    std::cout << "Printing reverse of the reverse array...\n";
    printArray(num, arr);
    ASSERT_EQ(0, arr[0]);
    ASSERT_EQ(24, arr[24]);
    ASSERT_EQ(49, arr[49]);

    return 0;
}

I am able to reverse the array, but when I put the "reversed" array back into the function, it seems to be of negative elements. I am not sure where this happens... Anything will help! The unit testing isn't the problem, but it is a part of the code. [1]: https://i.sstatic.net/MkfBC.png

Upvotes: 0

Views: 72

Answers (1)

WBuck
WBuck

Reputation: 5503

You have a bug with this line:

temparr[i] = *pointEnd - i;

Here you are dereferencing the pointEnd pointer and subtracting i from the resulting integer.

What you meant to write is:

temparr[i] = *( pointEnd - i );

Here you are subtracting i from the pointEnd pointer, then dereferencing.

That being said, instead of doing confusing pointer arithmetic why not do something like this instead:

temparr[ i ] = sequence[ arrayLength - i ];

Upvotes: 2

Related Questions