Swapping two structures in c

2020-05-29 08:33发布

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(struct StudentRecord *A, struct StudentRecord *B){
    struct StudentRecord *temp = *A;
    *A = *B;
    *B = *temp;
}


struct StudentRecord *pSRecord[numrecords];

for(int i = 0; i < numrecords; i++) {

pSRecord[i] = &SRecords[i];

}

printf("%p \n", pSRecord[0]);
printf("%p \n", pSRecord[1]);

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

printf("%p \n", pSRecord[0]);
printf("%p \n", pSRecord[1]);

2条回答
疯言疯语
2楼-- · 2020-05-29 08:59

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;
}
查看更多
Emotional °昔
3楼-- · 2020-05-29 09:18

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.

查看更多
登录 后发表回答