为什么结构数组的元素不交换?我正在尝试对学生结构数组进行排序。基于卷号
why elements of structure array are not swaping ? i am trying to sort array of student structure. based on roll no
我从 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;
}
您正在本地交换 swap
方法中的指针:它在函数之外不执行任何操作。
您必须取消对指针的引用才能使其有效,例如:
void swap(struct student *a,struct student *b)
{
struct student temp;
temp=*a;
*a=*b;
*b=temp;
}
这是因为您交换的是指针,而不是结构。
您可以像交换原语一样交换 struct
s,例如 int
s。这就是你交换两个通过指针传递给你的 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;
}
我从 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;
}
您正在本地交换 swap
方法中的指针:它在函数之外不执行任何操作。
您必须取消对指针的引用才能使其有效,例如:
void swap(struct student *a,struct student *b)
{
struct student temp;
temp=*a;
*a=*b;
*b=temp;
}
这是因为您交换的是指针,而不是结构。
您可以像交换原语一样交换 struct
s,例如 int
s。这就是你交换两个通过指针传递给你的 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;
}