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