Swapping two structures in c

前端 未结 2 1282

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

    First of all you do not have structs in your fragment, just the pointers to the structs. Therefore everything you do there is an attempt to swap pointers, not the struct values.

    Struct usually occupies multiple bytes somewhere in memory. A pointer is a variable which contains an address of this memory. It also occupies some memory, i.e. 8 bytes for a 64-bit address.

    The following is an array of pointers to the struct objects.

    struct StudentRecord *pSRecord[numrecords];
    

    which you initialized with addresses from the array of struct objects.

    This call looks like an attempt to swap pointers to the structs in your array. You did it correctly.

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

    however since pSRecord[i] is already a pointer to the struct and you take an address of the pointer &, the resulting object will be pointer to a pointer to a struct. Therefore your swap function needs **, like the following. And the rest of your code is correct:

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

提交回复
热议问题