Swapping two structures in c

前端 未结 2 1281

Hi i\'m trying to create a swap function that swaps the first two elements of the structure. Can someone please show me how to make this work.

void swap(struc         


        
2条回答
  •  长情又很酷
    2021-02-04 22:12

    The expression *A has type struct StudentRecord while the name temp is declared as having type struct StudentRecord *. That is temp is a pointer.

    Thus the initialization in this declaration

    struct StudentRecord *temp = *A;
    

    does not make sense.

    Instead you should write

    struct StudentRecord temp = *A;
    

    As result the function will look like

    void swap(struct StudentRecord *A, struct StudentRecord *B){
        struct StudentRecord temp = *A;
        *A = *B;
        *B = temp;
    }
    

    Take into account that the original pointers themselves were not changed. It is the objects pointed to by the pointers that will be changed.

    Thus the function should be called like

    swap(pSRecord[0], pSRecord[1]);
    

    If you want to swap the pointers themselves then the function will look like

    void swap(struct StudentRecord **A, struct StudentRecord **B){
        struct StudentRecord *temp = *A;
        *A = *B;
        *B = temp;
    }
    

    And in this statement

    swap(&pSRecord[0], &pSRecord[1]);
    

    you are indeed trying to swap pointers.

提交回复
热议问题