交换结构数组元素

Swapping struct array elements

我在应用按引用传递和按值传递分隔时遇到困难 structs.How 我可以按如下方式交换固定大小结构数组的元素吗?

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];*/

  }

有很多方法可以满足您的要求。一种方法:

#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;
}