Search code examples
cpass-by-referenceswappass-by-value

Swapping struct array elements


I have difficulty applying the pass by reference and pass by value separation in structs.How can I swap the elements of the fixed size struct array as below.

struct try{
   int num;
   char name[10];
 };
 int main(){
    struct try book[3];
    void swapper(/********/);//  <-what should be the argument of this function
  }
  void swapper(/********/){//swap second and third element of struct array
   /*how the swap may be done?
   temp=book[2];
   book[2]=book[3]; 
   temp=book[3];*/

  }

Solution

  • There are a lot of ways to do what you're asking. One approach:

    #include <stdio.h>
    
    struct try {
            int num;
            char name[10];
    };
    
    void
    swapper(struct try *a, int b, int c)
    {
            struct try tmp = a[b];
            a[b] = a[c];
            a[c] = tmp;
    }
    
    void
    display(const struct try *t, size_t count)
    {
            while( count-- ){
                    printf("%d: %s\n", t->num, t->name);
                    t += 1;
            }
    }
    
    int
    main(void) {
            struct try book[] = {
                    { 1, "foo"},
                    { 2, "bar"},
                    { 3, "baz"}
            };
            display(book, sizeof book / sizeof *book);
            swapper(book, 1, 2);
            display(book, sizeof book / sizeof *book);
            return 0;
    }