gpt4 book ai didi

c - 在c中交换两个结构

转载 作者:行者123 更新时间:2023-12-02 06:50:20 24 4
gpt4 key购买 nike

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

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]);

最佳答案

表达式 *A有类型 struct StudentRecord而名字temp被声明为具有类型 struct StudentRecord * .即 temp是一个指针。
因此这个声明中的初始化

struct StudentRecord *temp = *A;
没有意义。
相反,你应该写
struct StudentRecord temp = *A;
结果,该函数看起来像
void swap(struct StudentRecord *A, struct StudentRecord *B){
struct StudentRecord temp = *A;
*A = *B;
*B = temp;
}
考虑到原始指针本身没有改变。指针指向的对象将被改变。
因此该函数应该像
swap(pSRecord[0], pSRecord[1]);
如果您想交换指针本身,则该函数将如下所示
void swap(struct StudentRecord **A, struct StudentRecord **B){
struct StudentRecord *temp = *A;
*A = *B;
*B = temp;
}
在这个声明中
swap(&pSRecord[0], &pSRecord[1]);
您确实在尝试交换指针。

关于c - 在c中交换两个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46592887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com