Using pointers to swap int array values

前端 未结 7 1249
走了就别回头了
走了就别回头了 2021-01-05 17:57

I am supposed to use pointers to swap ints in an array. It compiles with no errors or warnings and runs but does not swap the ints. Any suggestions would be helpful!!!

相关标签:
7条回答
  • 2021-01-05 18:16

    Try this instead:

    void swap( int ary[] )
    {
        int temp = ary[0];
        ary[0] = ary[1];
        ary[1] = temp;
    }
    
    0 讨论(0)
  • 2021-01-05 18:26

    Examine your swap function more carefully:

    void swap( int ary[] )
    {
        int temp = *ary;
        *ary = *(ary + 1);
        *ary = temp;
    }
    

    When does *(ary + 1) get assigned to?

    0 讨论(0)
  • 2021-01-05 18:28

    You move the second value into the first spot, and then move the first value back into the first spot.

    0 讨论(0)
  • 2021-01-05 18:28

    You can also swap the values without any temporary variable:

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

    then call:

    swap(&ary[0], &ary[1]);
    
    0 讨论(0)
  • 2021-01-05 18:30

    just for fun; It's also possible to swap without using a temporary value

    void swap( int ary[] )
    {
        *ary ^= *(ary + 1);
        *(ary + 1) ^= *ary;
        *ary ^= *(ary + 1);
    }
    

    As GMan points out, this code obscures your intent from the compiler and the processor, so the performance may be worse than using a temp variable, especially on a modern CPU.

    0 讨论(0)
  • 2021-01-05 18:31

    I hate spoiling this but it looks like a typo more than anything.

    In your swap function:

    *ary = temp;
    

    should be:

    *(ary + 1) = temp;
    

    edit: Is there a reason you're not using array notation? I think it's a bit clearer for things like this:

    int temp = ary[0];
    ary[0] = ary[1];
    ary[1] = temp;
    
    0 讨论(0)
提交回复
热议问题