PDA

View Full Version : shifting array rows up




farmerdoug
Feb 20, 2012, 09:22 AM
I have an array of nxm elements.
I want to remove array[0]; move everything up; add something to array[n-1].

Do I use memcpy for the shifting? Is there a better way?

Thanks



subsonix
Feb 20, 2012, 09:32 AM
I have an array of nxm elements.
I want to remove array[0]; move everything up; add something to array[n-1].

Do I use memcpy for the shifting? Is there a better way?

Thanks

You can't use memcpy because if the memory regions overlap the behavior is undefined. You can use memmove() to do it, which is the same except that the memory regions may overlap (you can also do it manually of course).


int size = 10;
int a[] = {1,2,3,4,5,6,7,8,9,10};

memmove(a, a + 1, (size - 1) * sizeof(int));

farmerdoug
Feb 20, 2012, 11:30 AM
Thanks. This is good to know.

chown33
Feb 20, 2012, 11:52 AM
Thanks. This is good to know.

The caution about overlapping areas and memmove() is in memcpy's man page:
DESCRIPTION
The memcpy() function copies len bytes from memory area src to memory
area dst. If src and dst overlap, behavior is undefined. Applications
in which src and dst might overlap should use memmove(3) instead.

If you were using Bwana (http://bruji.com/bwana/), you could click man:memcpy and it would open the memcpy man page in your browser. The references to memmove and related functions would also be links in the presented man page.