【问题标题】:How to swap 2 integers using pointers?如何使用指针交换 2 个整数?
【发布时间】:2016-01-17 18:50:49
【问题描述】:

当我尝试使用指针交换这两个整数时,出现分段错误。

基本上在我交换之前,x 被分配给1y 被分配给2。在我交换后,x 被分配给2y 被分配给1

该程序采用两个整数 xy 并且据说是为了交换它们:

int swap(int x, int y){

    int *swapXtoY;
    int *swapYtoX;

    *swapXtoY = y;
    *swapYtoX = x;
}

【问题讨论】:

  • int swap(int x, int y) 方法接受两个整数,而不是两个指针。尝试关注int swap(int* x, int* y
  • *swapXtoY = y; 正在使用 未初始化的指针,而此未定义的行为通过将 y 写入有害或超出允许的内存分配。
  • 请注意,您缺少返回;

标签: c


【解决方案1】:

函数swap 期望它的两个参数都是int,但你传递的是int *。编译器应该对此提出警告。

您似乎不知道指针在 C 中是如何工作的。您的函数只是将两个 ints 分配给局部变量。函数应该是这样的:

int swap(int *x, int *y){

    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

【讨论】:

    【解决方案2】:

    swap 方法应该接受两个指针,而不是两个整数。
    尝试关注。

    int swap(int* x, int* y){
      int temp = *x;
      *x = *y;
      *y = temp;    
    }
    

    【讨论】:

    • int * temp --> int temp
    【解决方案3】:

    您必须通过地址将变量传递给函数以更改其值。话虽如此,您的函数也应该期望指针。这是一个通用函数,可以交换任何C 数据类型的变量:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    void Swap(void *x,void *y,size_t bytes);
    
    int main(void)
    {
        int x = 3, y = 4;
        Swap(&x,&y,sizeof(int));
        printf("x now : %d\n",x);
        printf("y now : %d\n",y);
        return 0;
    }
    void Swap(void *x,void *y,size_t bytes)
    {
        void *tmp = malloc(bytes);
        memcpy(tmp,x,bytes);
        memcpy(x,y,bytes);
        memcpy(y,tmp,bytes);
        free(tmp);
    }
    

    【讨论】:

      【解决方案4】:

      首先,您的函数按值传递其参数1,这使得函数无法对它们进行任何持久的更改。

      其次,交换习语包括:

      • 定义一个中间变量temp,它被初始化为两个变量之一,例如x

      • 将第二个变量y的值赋给第一个(保存在temp中)变量x (现在temp的值是@987654329 @ 和 x 的值是 y)

      • 最后,将temp赋值给第二个变量y(现在x的值是y,反之亦然)

      在 C 代码中,这看起来像:

      void swap (int *x, int *y ) {
      
          // dereference x to get its value and assign it to temp
          int temp = *x; 
      
          // dereference x and assign to it the value of y
          *x = *y;
      
          // complete the swap
          *y = temp;
      }
      

      然后调用函数:

      // if the variables are not pointers
      swap(&x, &y);
      
      // if variables are passed via pointers
      swap(x_ptr, y_ptr);
      

      您可能需要检查dereference operator *address-of operator & 的含义。


      1.按值:它传递所传递变量的副本,从而防止函数外的任何更改。

      【讨论】:

        猜你喜欢
        • 2021-01-14
        • 1970-01-01
        • 2014-08-16
        • 2014-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多