Copying arrays of structs in C

后端 未结 6 960
后悔当初
后悔当初 2021-02-06 12:03

It\'s been a long since I don\'t use C language, and this is driving me crazy. I have an array of structs, and I need to create a function which will copy one array to another (

6条回答
  •  误落风尘
    2021-02-06 12:42

    This has a feel of poorly masqueraded homework assignment... Anyway, given the predetermined call format for copySolution in the original post, the proper definition of copySolution would look as follows

    void copySolution(struct group (*a)[4], struct group (*b)[4])
    {
      /* whatever */
    }
    

    Now, inside the copySolution you can copy the arrays in any way you prefer. Either use a cycle

    void copySolution(struct group (*a)[4], struct group (*b)[4])
    {
      const struct group *pb, *pbe;
      struct group *pa;
    
      for (pa = *a, pb = *b, pbe = pb + sizeof *b / sizeof **b; 
           pb != pbe; 
           ++pa, ++pb)
        *pa = *pb;
    }
    

    or use memcpy as suggested above

    void copySolution(struct group (*a)[4], struct group (*b)[4])
    {
      memcpy(b, a, sizeof *b);
    }
    

    Of course, you have to decide first which direction you want your arrays to be copied in. You provided no information, so everyone just jumped to some conclusion.

提交回复
热议问题