Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

farmerdoug

macrumors 6502a
Original poster
Sep 16, 2008
541
0
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
 
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).

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

    memmove(a, a + 1, (size - 1) * sizeof(int));
 
Thanks. This is good to know.

The caution about overlapping areas and memmove() is in memcpy's man page:
Code:
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, 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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.