Reverse order of Integer array.

Hello this is a noob programming question, but i just cant get it to work.
Im trying to take my int array named "buffer" and reverse the order of all numbers in it, and put it in a new array named "buffer2".
Any tips on how i can achieve this?
Thanks in advance.

int x = 0;
int y = 255; //CHANGE TO SIZE OF "BUFFER" ARRAY!

while(y){
  buffer[x] = buffer2[y];
  x++;
  y--;
}

Remember to change the size of 'y' to the size of 'buffer'.
Onions.

an inplace reverse

#define BUFFERSIZE 123
int buffer[BUFFERSIZE];

reverse()
{
  for (int i=0, j = BUFFERSIZE-1; i< BUFFERSIZE/2; i++, j--)
  {
    int temp = buffer[i];
    buffer[i] = buffer[j];
    buffer[j] = temp;
  }
}

Big thanks for the fast reply! Great support!

Onions:

int x = 0;

int y = 255; //CHANGE TO SIZE OF "BUFFER" ARRAY!

while(y){
 buffer[x] = buffer2[y];
 x++;
 y--;
}




Remember to change the size of 'y' to the size of 'buffer'.
Onions.

So maybe use: int y = sizeof(buffer); ?

retrolefty:
So maybe use: int y = sizeof(buffer); ?

Which of course only works if you're not passing the array as an argument to a function.

retrolefty:
So maybe use: int y = sizeof(buffer); ?

No, because 'sizeof' returns the number of bytes in the array, not the number of elements. Since an 'int' is two bytes on the Arduino, 'sizeof' will return twice the number of elements. Try this:

int y = sizeof(buffer) / sizeof(buffer[0]);

Remember that the compiler will evaluate the two 'sizeof's and the division.

for (int i=0, j = BUFFERSIZE-1; i< BUFFERSIZE/2; i++, j--)
  {
    int temp = buffer[i];
    buffer[i] = buffer[j];
    buffer[j] = temp;
  }

Bonus marks for eliminating "temp"

AWOL:
Bonus marks for eliminating "temp"

I'll just leave this here: XOR swap algorithm - Wikipedia

Without the int j, but I expect it will execute slower; pointer math might be faster

for (int i=0; i< BUFFERSIZE/2; i++)
  {
    int temp = buffer[i];
    buffer[i] = buffer[BUFFERSIZE-1 - i ];
    buffer[BUFFERSIZE-1 - i] = temp;
  }

I'll just leave this here: XOR swap algorithm - Wikipedia

Opacity, I agree with.
"Modern CPU architecture" and "AVR" don't fit in the same sentence :wink:

Well, the AVR chips do have a pipeline (even though that can easily be ignored). But I was actually mostly referring to compiler optimizations.

Well, the AVR chips do have a pipeline

PICs do too - I wonder why they're so slow?