在c中交换两个结构 [英] Swapping two structures in c

查看:92
本文介绍了在c中交换两个结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi i'm trying to create a swap function that swaps the first two elements of the structure. Can someone please show me how to make this work.

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是一个指针.

The expression *A has type struct StudentRecord while the name temp is declared as having type struct StudentRecord *. That is temp is a pointer.

因此该声明中的初始化

struct StudentRecord *temp = *A;

没有道理.

您应该写

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;
}

在此声明中

swap(&pSRecord[0], &pSRecord[1]);

您确实在尝试交换指针.

you are indeed trying to swap pointers.

这篇关于在c中交换两个结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆