在c中交换两个结构

Eth*_*tch 0 c swap struct pointers

嗨,我正在尝试创建交换函数,以交换结构的前两个元素。有人可以告诉我如何使这项工作。

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]);
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 6

表达*A具有类型struct StudentRecord而名称temp被声明为具有类型struct StudentRecord *。那temp是一个指针。

因此,此声明中的初始化

struct StudentRecord *temp = *A;
Run Code Online (Sandbox Code Playgroud)

没有道理。

相反,你应该写

struct StudentRecord temp = *A;
Run Code Online (Sandbox Code Playgroud)

结果,该功能看起来像

void swap(struct StudentRecord *A, struct StudentRecord *B){
    struct StudentRecord temp = *A;
    *A = *B;
    *B = temp;
}
Run Code Online (Sandbox Code Playgroud)

考虑到原始指针本身未更改。指针所指向的对象将被更改。

因此,该函数应像

swap(pSRecord[0], pSRecord[1]);
Run Code Online (Sandbox Code Playgroud)

如果您想交换指针本身,则该函数将如下所示

void swap(struct StudentRecord **A, struct StudentRecord **B){
    struct StudentRecord *temp = *A;
    *A = *B;
    *B = temp;
}
Run Code Online (Sandbox Code Playgroud)

在这句话中

swap(&pSRecord[0], &pSRecord[1]);
Run Code Online (Sandbox Code Playgroud)

您确实在尝试交换指针。