Swapping two structures in c

六月ゝ 毕业季﹏ 提交于 2019-12-03 21:59:30

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.

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!