c - 为什么结构体数组的元素不交换?我正在尝试对学生结构数组进行排序。根据卷号

标签 c structure quicksort

从 main() 中,我正在调用函数,其中记录是 struct.in swap() 函数的数组,我看到地址正在交换,但在分区中它显示原始地址。

quick_sort(记录,0,MAXNO-1);

void quick_sort(struct student arr[],int left,int right)
{
        int pi;
        if(left<right)
        {
                pi=partation(arr,left,right);
                quick_sort(arr,left,pi-1);
                quick_sort(arr,pi+1,right);
        }
 }
int partation(struct student str[],int low,int high)
{
        int i,j;
        struct student pivot=str[high];
        i=low-1;
        for(j=0;j<high;j++)
        {
                if(str[j].rollno < pivot.rollno)
                {
                        i++;
                        swap(&str[i],&str[j]);
                }
        }
        swap(&str[i+1],&str[j]);
        return i+1;
}
void swap(struct student *a,struct student *b)
{
        struct student *temp;
        temp=a;
        a=b;
        b=temp;
}

最佳答案

这是因为您正在交换指针,而不是结构。

您可以按照交换基元(例如 int)的相同方式交换struct。这是交换通过指针传递给您的两个 int 的方式:

void swap(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = temp;
}

struct 的代码几乎相同:

void swap(struct student *a, struct student *b) {
    struct student temp = *a;
    *a = *b;
    *b = temp;
}

关于c - 为什么结构体数组的元素不交换?我正在尝试对学生结构数组进行排序。根据卷号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43679398/

相关文章:

c++ - #include <mysql.h> & #include <my_global.h> 导致编译错误

c++ - Matlab 到 OpenCV 的转换 - 优化?

此类内容的 MySQL 结构?

Python快速排序-在终端上运行的递归错误

arrays - 我在使用快速排序算法时遇到问题

c - UDS 套接字上的 send() 返回而不发送整个数据。为什么?

c - 为什么 sizeof(msg) 比字符串短?

version-control - 在处理许多具有通用代码库的小项目时,良好的 github 结构?

c - 为什么将结构地址转换为 int 指针、取消引用并将其用作语句中的 LVALUE 会使我的微 Controller 崩溃?

c - 快速排序运行时速度问题