Using pointers to swap int array values

▼魔方 西西 提交于 2019-11-30 05:20:13

问题


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!!!

Here is the tester:

#import <stdio.h>

void swap( int ary[] );

int main(  int argc, char*argv[] )
{
    int ary[] = { 25, 50 };
    printf( "The array values are: %i and %i \n", ary[0], ary[1] );
    swap( ary );
    printf( "After swaping the values are: %i and %i \n", ary[0], ary[1] );

    return 0;
}

Here is the swap function:

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

This is what is displayed after running:

The array values are: 25 and 50
After swaping the values are: 25 and 50

回答1:


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;



回答2:


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?




回答3:


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




回答4:


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.




回答5:


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]);



回答6:


Try this instead:

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



回答7:


your swap function will work only for 2-ints array, so show it to your compiler (it won't change anything, but make code cleaner)

void swap( int ary[2] )


来源:https://stackoverflow.com/questions/1670821/using-pointers-to-swap-int-array-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!