C

Copying Arrays of Structures in C

roland's picture
My question is what would happen if you did array1[i] = array2[i] vs array1 = array[2]. The first works like *pointer1 = *pointer2, the latter is ambiguous. hmmm.
#include 

struct x {
  int y;
  int z;
};

int main() {
  struct x a[5];
  struct x b[5];

  int i;
  for(i = 0; i < 5; i++) {
    a[i].y = i;
    a[i].z = 100+i;
  }

  for(i = 0; i < 5; i++) {
    b[i] = a[i];
  }


  for(i = 0; i < 5; i++) {
    printf("%d -> %d\t %d -> %d\n", a[i].y, b[i].y, a[i].z, b[i].z);
  }
  
  printf("------------------------\n");

  a[3].y = 10;

  for(i = 0; i < 5; i++) {
    printf("%d -> %d\t %d -> %d\n", a[i].y, b[i].y, a[i].z, b[i].z);
  }
  
  printf("\n");
  return 0;
} 

Result:

0 -> 0	 100 -> 100
1 -> 1	 101 -> 101
2 -> 2	 102 -> 102
3 -> 3	 103 -> 103
4 -> 4	 104 -> 104
------------------------
0 -> 0	 100 -> 100
1 -> 1	 101 -> 101
2 -> 2	 102 -> 102
10 -> 3	 103 -> 103
4 -> 4	 104 -> 104
Syndicate content