Advertisement
Guest User

array shift

a guest
May 25th, 2010
944
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.03 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <strings.h>
  3. #include <stdlib.h>
  4. #include <sys/types.h>
  5.  
  6. int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  7. const int arrlen = sizeof(arr) / sizeof(int);
  8.  
  9. void dump(int a[], size_t nmemb)
  10. {
  11.     register int i;
  12.  
  13.     for(i = 0; i < nmemb; i++)
  14.         printf("%s%d", i ? ", " : "", a[i]);
  15.  
  16.     printf("\n");
  17. }
  18.  
  19. void shift(int a[], size_t nmemb, int dst)
  20. {
  21.     int left = dst < 0;
  22.  
  23.     dst = abs(dst) % nmemb;
  24.  
  25.     printf("SHIFT: nmemb=%d ; dst=%d ; left=%d\n", nmemb, dst, left);
  26.  
  27.     if(dst)
  28.     {
  29.         int b[dst];
  30.  
  31.         if(left)
  32.         {
  33.             bcopy(a, b, dst * sizeof(int));
  34.             bcopy(&a[dst], a, (nmemb - dst) * sizeof(int));
  35.             bcopy(b, &a[nmemb - dst], dst * sizeof(int));
  36.         }
  37.         else
  38.         {
  39.             bcopy(&a[nmemb - dst], b, dst * sizeof(int));
  40.             bcopy(a, &a[dst], (nmemb - dst) * sizeof(int));
  41.             bcopy(b, a, dst * sizeof(int));
  42.         }
  43.     }
  44. }
  45.  
  46. int main(int argc, char *argv[])
  47. {
  48.     printf("START:");
  49.     dump(arr, arrlen);
  50.  
  51.     shift(arr, arrlen, 4);
  52.  
  53.     dump(arr, arrlen);
  54.  
  55.     shift(arr, arrlen, -4);
  56.  
  57.     dump(arr, arrlen);
  58.  
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement