c - 为什么在使用指针交换两个变量时会得到意想不到的结果?

标签 c pointers

这是我在使用函数 selectionSort(int *,int) 执行选择排序时使用指针交换变量的两个函数。但是排序后,数组的某些元素变为零。

void selectionSort(int *x,int len){
    int i,j,max;
    for(i=len-1;i>=0;i--){
        max = 0;
        for(j=1;j<=i;j++){
            if(x[j]>x[max]){
                max = j;
            }
        }
        swap(x+max,x+i);
    }
}

void swap(int *a,int *b){
    //This one works perfectly
    int temp;
    temp=*b;
    *b=*a;
    *a=temp;
}


void swap(int *a,int *b){
    //This one gives unexpected results
    *a=*a+*b;
    *b=*a-*b;
    *a=*a-*b;
}

最佳答案

使用算术运算符交换两个整数可能会导致整数溢出。最好坚持使用传统方法。

顺便说一句,您可以使用老派的按位 XOR 运算符进行交换(用于交换寄存器中的值),但与使用临时变量的方法相比,它不会给您带来任何好处。如今,编译器足够聪明,可以优化代码。

if (*a == *b) // If both integers are same then do not perform swap operation
    return;

*a ^= *b;
*b ^= *a;
*a ^= *b;

关于c - 为什么在使用指针交换两个变量时会得到意想不到的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45608385/

相关文章:

c - sscanf 读取它不应该读取的内容

C 编程语言练习 1-18

c - 如何在C中输入由换行符分隔的两个字符串

c - 跳过 read 语句到 printf 语句

C++:为指向两种类型之一的指针保留打开选项

c - 将 C 结构迁移到 Delphi 记录

c - 将指针传递给 C 中的另一个函数

c - Str[Col][Row] 中的 Str 是 "pointer"还是 "pointer to pointer"?

在 C 中转换指向 int 的指针

C++ 指针容器