使用指针交换 int 数组值
我应该使用指针来交换数组中的整数。它编译时没有错误或警告并运行,但不交换整数。任何建议都会有帮助!
这是测试器:
#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;
}
这是交换函数:
void swap( int ary[] )
{
int temp = *ary;
*ary = *(ary + 1);
*ary = temp;
}
这是运行后显示的内容:
The array values are: 25 and 50
After swaping the values are: 25 and 50
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我讨厌破坏这个,但它看起来更像是一个打字错误。
在您的交换函数中:
应该是:
编辑:您不使用数组表示法有原因吗?我认为对于这样的事情来说更清楚一些:
I hate spoiling this but it looks like a typo more than anything.
In your swap function:
should be:
edit: Is there a reason you're not using array notation? I think it's a bit clearer for things like this:
更仔细地检查您的交换函数:
*(ary + 1)
何时被分配到?Examine your swap function more carefully:
When does
*(ary + 1)
get assigned to?将第二个值移至第一个位置,然后将第一个值移回第一个位置。
You move the second value into the first spot, and then move the first value back into the first spot.
只是为了好玩;也可以在不使用临时值的情况下进行交换,
正如 GMan 指出的那样,这段代码掩盖了编译器和处理器的意图,因此性能可能比使用临时变量更差,尤其是在现代 CPU 上。
just for fun; It's also possible to swap without using a temporary value
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.
您还可以在没有任何临时变量的情况下交换值:
然后调用:
You can also swap the values without any temporary variable:
then call:
试试这个:
Try this instead:
您的交换函数仅适用于 2-ints 数组,因此请将其显示给您的编译器(它不会改变任何内容,但会使代码更清晰)
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)