c - 在c中交换两个结构

标签 c pointers struct swap

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

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/

相关文章:

c++ - 如何添加到对象数组指针C++

java - 链表和指针插入列表的冗余序列化

c - 将二进制文件读入结构变量,出现段错误

c - 打开 Watcom Linker 在链接 C 和 Fortran 代码以构建 Matlab mex 文件时发现 undefined reference

c - 创建双向链表时出现段错误

服务器应用程序中的 C 内存管理

c - 如何在 C 中定义全局变量 "struct"

c - **在C语言中是什么意思?

c - 如何释放()我的变量

c - 为什么我的 C 程序不能正常工作?