shifting array rows up

Discussion in 'Mac Programming' started by farmerdoug, Feb 20, 2012.

  1. farmerdoug macrumors 6502a

    Sep 16, 2008
    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?

  2. subsonix macrumors 68040

    Feb 2, 2008
    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));
  3. farmerdoug thread starter macrumors 6502a

    Sep 16, 2008
  4. chown33 macrumors 604

    Aug 9, 2009
    Sailing beyond the sunset
    The caution about overlapping areas and memmove() is in memcpy's man page:
         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.

Share This Page