我应该使用指针来交换数组中的整数。它在没有错误或警告的情况下编译并运行但不交换整数。任何建议都会有帮助!!!
这是测试人员:
#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
最佳答案
我不想破坏它,但它看起来更像是一个打字错误。
在你的交换函数中:
*ary = temp;
应该是:
*(ary + 1) = temp;
编辑:您有没有使用数组表示法的原因?我认为这样的事情更清楚一些:
int temp = ary[0];
ary[0] = ary[1];
ary[1] = temp;
关于c - 使用指针交换 int 数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1670821/