# Thread: Shifting elements in an Array

1. ## Shifting elements in an Array

Hi,

Was wondering if anyone could help, basically i want to shift some elements in an array when new ones are added.

For Example:

My Array contains: <1,2,3,4,5>
Then i add the following elements: 6 and 7
So i would like my array to end up looking like this: <3,4,5,6,7>

So basically when a new element is added, it removes the first one, shifts the others a long and then addeds the new one elements at the end.

Just wondering if someone could help explain to me the best way to do this.

Thanks Code:
```for(i=0,j=1;i<n;i++,j++)
{

if(i==(n-1))
{
arr[i]=new_number;
}
else
arr[i]=arr[j];
}``` 3. Much cleaner and easier code:
Code:
```int main()
{
int i, j, length = 5, elem_to_shift = length;
int myarray = { 1, 2, 3, 4, 5 };

for (i = 0; i < 2; i++)
{
for (j = 0; j < elem_to_shift - 1; j++)
{
/* Move elements backwards */
myarray[j] = myarray[j + 1];
}
elem_to_shift--;
}
myarray = 6;
myarray = 7;
}```
Or maybe
Code:
```int main()
{
int myarray = { 1, 2, 3, 4, 5 };
memmove(myarray, &myarray, 4);
myarray = 6;
}```
The second example doesn't seem to work, though.
Since memmove is assembly, I don't really know why it doesn't work, though technically it should. 4. We all make mistakes. memmove copies bytes, as you might recall. The following works good.
Code:
```#include <stdio.h>
#include <string.h>

int main ( void )
{
int ar[] = { 1, 2, 3, 4, 5, };
const int N = sizeof ar / sizeof ar;
int i;

memmove( ar, &ar[N - newest - 1], (N - newest) * sizeof ar );
ar = 6;
ar = 7;

for ( i = 0; i < N; i++ ) printf( "%d\n", ar[i] );
return 0;
}``` 5. Originally Posted by Elysia Much cleaner and easier code:
Yes, and unfortunately much more incorrect. I know we've recently had somone who was moving elements over in an array and they needed to copy them backwards, but in this instance, the items are being moved towards, the lower index (to the left). So you actually have to specifically NOT copy them backwards for it to work in this case.
Not to mention the code you posted suffers from buffer underrun as well.

If moving to the left, always copy forwards, if moving to the right, always copy backwards. This is exactly what memmove does. 6. Is it? Take a look again  Popular pages Recent additions 