简体   繁体   中英

C++ Reversing an array not giving expected output

I'm trying to reverse an int array using pointer incrementing/decrementing. When I run it, it reverses to the halfway point in the array, and then stops and goes backwards.

This is the result that I'm currently getting:

Array size: 10

Original array:
   42   68   35    1   70
   25   79   59   63   65

Reversed array:
   65   63   59   79   25
   25   79   59   63   65

Expected outcome:
   65   63   59   79   25
   70    1   35   68   42

This is the algorithm I'm using:

int temp = 0;
lastElement = &data[size - 1];

for (int i = 0; i < size; i++)
{
    *(data) = *(lastElement);

    data++;
    lastElement--;
}

EDIT:

Working algorithm:

first = data;
last = &data[size - 1];

for (int i = 0; i < size / 2; i++)
{
    int temp = *first;
    *first = *last;
    *last = temp;
    first++;
    last--;
}

If you swap half of an array for the other half, you've swapped the entire array. If you swap the first half for the second half and then swap the second half with the first half, you're back where you started. Don't do that.

As your algorithm uses pointers at beginning and end of array, so each step of the loop swaps two elements. Thus your loop should have array size/2 steps (middle element if any stays in the current position).

first= data;
last = &data[size - 1];

for (int i = 0; i < size/2; i++)
{
    int temp = *first;
    *first = *last;
    *last = temp;
    first++;
    last--;
}

I recommend to get familiar with STL , especially STL algorithms . There is reverse algorithm (see linked documentation with nice example).

Change the for loop to be something like this:

for (int i = 0; i < size / 2; i++)
{
  std::swap(*data, *lastElement);  

  data++;
  lastElement--;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM