从 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/