Search code examples
cstructswapitems

How to swap struct elements of array inside a struct - C


I have 2 structs

typedef struct {
    int i;
    int p;
} item;

typedef struct {
    item items[10];
} buffer;

void swap (item** p1, item** p2) {
   item* temp = *p1;
  *p1 = *p2;
  *p2 = temp;
}

im trying to call

    item *ps = &buffer.items[0];
    item *p = &buffer.items[1];

    swap(&ps, &p);

but it is not swapping them? What am I doing wrong? Thanks would there be any change if the struct buffer was local in main or global?

Thanks


Solution

  • Your function only swaps the pointers ps and p, not the actual structures they point to. For that you need to copy the structures, something like

    void swap (item* p1, item* p2) {
       item temp = *p1;
      *p1 = *p2;
      *p2 = temp;
    }
    

    Call as

    swap(&buffer.items[0], &buffer.items[1]);