1. 程式人生 > >用“指標法”交換陣列中10個元素的先後順序

用“指標法”交換陣列中10個元素的先後順序

交換陣列中10個元素的先後順序,結果如下:

enter 10 numbers:15   26   34   75   95   26   34   25   26   10
source data:15   26   34   75   95   26   34   25   26   10
the first element of array:15
has been swap:10   26   25   34   26   95   75   34   26   15

註釋:transfer:呼叫       function:函式       element:元素      same as:與……相同      swap:交換

#include <stdio.h>
#include <string.h>
#define N 10
void main()
{
void swap(int array[]);
int i,*p,array[N];
printf("Enter %d numbers:",N);
for(p=array;p<array+N;p++)
scanf("%d",p);
printf("source data:");
for(p=array;p<array+N;p++)
printf("%-4d",*p);
printf("/n");
swap(array);/transfer function "swap"/
printf("has been swap:");
for(i=0;i<N;i++)
printf("%4d",array[i]);
putchar('/n');
}

void swap(int *array)
{
int *p,*p2,temp;
printf("The firsit element of array:%d/n",*array);/*the "*array" mean is first element*/
for(p2=&array[N-1],p=array;p<p2;p++,p2--)  /*the "p=array" same as "p=&array[0]"*/
{
temp=*p;
*p=*p2;
*p2=temp;
}
return;