shifting array rows up

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

  1. macrumors 6502a

    Joined:
    Sep 16, 2008
    #1
    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
     
  2. macrumors 68040

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

    Joined:
    Sep 16, 2008
  4. macrumors 603

    Joined:
    Aug 9, 2009
    #4
    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.
     

Share This Page