【问题标题】:Swapping two structures in c在c中交换两个结构
【发布时间】:2017-10-05 18:55:00
【问题描述】:

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

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

【问题讨论】:

  • 最好将temp 设为值,而不是指针。
  • struct StudentRecord *temp = *A; --> struct StudentRecord temp = *A;.. *B = *temp; --> *B = temp;.....swap(&amp;pSRecord[0], &amp;pSRecord[1]); --> swap(pSRecord[0], pSRecord[1]);swap(&amp;SRecords[0], &amp;SRecords[1]);
  • 除此之外:不是每个人都厌倦了包含“学生”的 C 代码。所以世界各地的所有老师都布置相同的作业?
  • @FredLarson:指针值。
  • @Olaf:当然,我指的是结构的值。

标签: c pointers struct swap


【解决方案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]);

您确实在尝试交换指针。

【讨论】:

    【解决方案2】:

    首先,片段中没有结构,只有指向结构的指针。因此,您所做的一切都是试图交换指针,而不是结构值。

    结构通常在内存的某个地方占用多个字节。指针是一个包含该内存地址的变量。它还占用一些内存,即 8 个字节用于 64 位地址。

    以下是指向结构对象的指针数组。

    struct StudentRecord *pSRecord[numrecords];
    

    您使用结构对象数组中的地址进行初始化。

    这个调用看起来像是试图交换指向数组中结构的指针。你做得对。

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

    然而,由于 pSRecord[i] 已经是一个指向结构的指针,并且您获取指针&amp; 的地址,因此生成的对象将是指向结构的指针的指针。因此,您的交换功能需要**,如下所示。你的其余代码是正确的:

    void swap(struct StudentRecord **A, struct StudentRecord **B) {
        struct StudentRecord *temp = *A;
        *A = *B;
        *B = *temp;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多